Home  >  Article  >  Web Front-end  >  How to change the image address with javascript

How to change the image address with javascript

青灯夜游
青灯夜游Original
2022-01-19 11:57:128002browse

Javascript method to change the image address: 1. Use the "document.getElementById("id")" statement to obtain the image object according to the specified id value; 2. Use "image object.setAttribute("src","New Image address ");" statement to change the image address.

How to change the image address with javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to change the image address in javascript

Implementation idea:

  • First get the img image object (The How to change the image address with javascript tag defines the image in the HTML page.)

  • Then use the setAttribute() method to reset the value of the src attribute (the src attribute of the img tag specifies the URL of the image .)

#setAttribute() method adds the specified attribute and assigns it the specified value. If this specified property already exists, the value is only set/changed.

Implementation code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<img  id="img" src="img/3.jpg"    style="max-width:90%"/ alt="How to change the image address with javascript" ><br>
		<button onclick="myFunction()">更改图片地址</button>
		<script>
			function myFunction() {
				var img=document.getElementById("img");
				img.setAttribute("src","img/4.jpg");
			}
		</script>
	</body>
</html>

How to change the image address with javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to change the image address with javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn