Javascript将图像加载到悬停在链接上

Javascript将图像加载到悬停在链接上,javascript,Javascript,我不熟悉java脚本,我正在设计我的网站,但当用户悬停在主页上时,我想在网页的特定位置加载一个新的图像,下面是代码 <html> <head> </head> <body> <img src="yourImage.jpg" alt="Home" id="image1" onmouseover="image1.src='home.jpg';" onmouseout=

我不熟悉java脚本,我正在设计我的网站,但当用户悬停在主页上时,我想在网页的特定位置加载一个新的图像,下面是代码

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


此代码无效。请帮助我找出代码中的错误。

  • image1
    没有任何意义。您需要使用
    document.getElementById('image1').src
    而不仅仅是
    image1.src
  • 您缺少的
    onmouseover
    属性的起始引号
    a
    标记

在尝试操作图像对象之前,必须使用方法
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来做这样的事情。除了不使用Doop.GETelEnMyByID之外,你也会遇到鼠标上的滞后,除非图像已经预加载。

< P>你不能引用IMG作为<代码> IMAGE.Src 首先你必须赋权<代码> IMAG1=文档.GETelEnMyByID(“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>



要从img元素自身的内联属性访问img元素,需要使用“this”关键字:

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

您也可以使用javascript库(如jQuery)而不是内联执行,这将为您提供更大的灵活性,如果您以后想执行更多操作(例如添加动画),但这取决于您和您感觉的挑战程度:)