i am new to java script and i am designing my web site but i want to load a new image on a particular place of my web page when a user hover over the home,here is the code.
<html>
<head>
</head>
<body>
<img src="yourImage.jpg" alt="Home" id="image1" onmouseover="image1.src='home.jpg';" onmouseout="image1.src='myImage.jpg';" /> <br />
<a href="#" onmouseover=image1.src='home.jpg';" onmouseout="image1.src='yourImage.jpg';">Hoover Me!</a>
</body>
</html>
This code is not working.Please Help me to find out the error in code.
You have to use the method document.getElementById()
to get the image object before try to manipulate it:
<body>
<img src="yourImage.jpg" alt="Home" id="image1" onmouseover="document.getElementById('image1').src='home.jpg';" onmouseout="document.getElementById('image1').src='myImage.jpg';" /> <br />
<a href="#" onmouseover="document.getElementById('image1').src='home.jpg';" onmouseout="document.getElementById('image1').src='yourImage.jpg';">Hoover Me!</a>
</body>
You should consider using JQuery to do this kind of stuff.
image1
doesn't have any meaning. You will need to use document.getElementById('image1').src
instead of just image1.src
. onmouseover
attribute of the a
tag. 除了不使用document.getElementById,您还将在鼠标悬停时遇到延迟,除非已预先加载了图像。
You can not refer to the img as image1.src
first you have to assign image1=document.getElementById('image1')
then you can refer it as image1.src
. There is also a much simpler method to do that. You can also refer to the current image or object as this.src
in JavaScript. See the corrected code with changes bellow:
<html>
<head>
</head>
<body>
<img src="yourImage.jpg" alt="[ Home ]" id="image1" onmouseover="this.src='home.jpg';" onmouseout="this.src='myImage.jpg';" /><br />
<a href="#" onmouseover="document.getElementById('image1').src='home.jpg';" onmouseout="document.getElementById('image1').src='yourImage.jpg';">Hoover Me!</a>
</body>
</html>
To access the img element from it's own inline attributes, you need to use the 'this' keyword:
<img src="yourImage.jpg" alt="Home" id="image1" onmouseover="this.src='yourOtherImage.jpg';" />
Rather than do it inline, you could also use a javascript library, like jQuery, as detailed here , which would give you more flexibility if you want to do more later eg add animations, but that's up to you and how much of a challenge you feel like :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.