2011-11-29 67 views
0

我是新来的Java脚本,我设计我的网站,但我想加载一个新的图像在我的网页的特定位置时,用户悬停在家里,在这里是代码。Javascript加载图像时悬停在一个链接

 <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> 

此代码不工作。请帮助我找出代码中的错误。

回答

0

您不能参考img image1.src首先您必须指定image1=document.getElementById('image1')然后您可以将其引用为image1.src。还有一个更简单的方法来做到这一点。您也可以在JavaScript中将当前图像或对象称为this.src。见有变化更正后的代码波纹管:

<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> 
0
  • image1没有任何意义。您将需要使用 document.getElementById('image1').src而不仅仅是image1.src
  • 您错过了onmouseover属性的起始报价 a标记。
1

您必须使用方法document.getElementById()以获取图像对象之前试图操纵它:

<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> 

你应该考虑使用jQuery做这种东西。

0

除了不使用document.getElementById,您还会遇到鼠标悬停的延迟,除非图像已预先加载。

0

从它自己的内联属性访问img元素,你需要使用“这个”关键词:

<img src="yourImage.jpg" alt="Home" id="image1" onmouseover="this.src='yourOtherImage.jpg';" /> 

而不是内联做,你也可以使用像jQuery这样的javascript库,详见here,如果你想在后面做更多的话,这会给你更多的灵活性,例如添加动画,但这取决于你和你有多大的挑战,你觉得:)