Javascript 鼠标悬停在 html 上更改图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13587391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:25:12  来源:igfitidea点击:

on mouse over change image on html

javascripthtmlimagemouseover

提问by 33528

I was trying to make an image to change on mouse over. This piece of code works for IE but not for the other browsers like chrome, opera, safari, etc. Any ideas?

我试图制作一个图像以在鼠标悬停时改变。这段代码适用于 IE,但不适用于 chrome、opera、safari 等其他浏览器。有什么想法吗?

<a href="#" onmouseover="document.myimage1.src='img/login_button_22.jpg';"
onmouseout="document.myimage1.src='img/login_button_11.jpg';">    
<img src="img/login_button_11.jpg" name="myimage1" /> </a>

回答by Diodeus - James MacFarlane

You should be using a ID, not a NAME, and using document.getElementByIdto select the element.

您应该使用 ID,而不是 NAME,并document.getElementById用于选择元素。

IMG elements, not being FORM elements, should not be able to take on a NAME property, but Microsoft managed to screw this up.

IMG 元素,不是 FORM 元素,不应该具有 NAME 属性,但微软设法搞砸了。

<a href="#" onmouseover="document.getElementById('myimage1').src='img/login_button_22.jpg';"
onmouseout="document.getElementById('myimage1').src='img/login_button_11.jpg';">    
<img src="img/login_button_11.jpg" id="myimage1" /></a>

Also, it's much easier and cleaner to use a CSS background and a :hoverdeclaration and skip doing this using JavaScript completely.

此外,使用 CSS 背景和:hover声明并完全跳过使用 JavaScript 执行此操作会更容易和更清晰。

Here's how:

就是这样:

HTML:

HTML:

<a class="mybutton" href="#"></a>

CSS (adjust dimensions accordingly):

CSS(相应地调整尺寸):

.myButton {
     width:100px;
     height:50px;
     display:block;
     background-image:url(../img/login_button_11.jpg);

}

.myButton:hover {
     background-image:url(../img/login_button_22.jpg)
}

回答by Sad Danbo

<a href="" onMouseOver="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/ask-icon.png';" onMouseOut="document.MyImage.src='http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png';">
<img src="http://icons.iconarchive.com/icons/uiconstock/round-edge-social/72/arto-icon.png" name="MyImage">

Demo http://jsfiddle.net/W6zs5/

演示 http://jsfiddle.net/W6zs5/

回答by kurdtpage

Try this:

尝试这个:

<img src='img/login_button_11.jpg' onmouseover="this.src='img/login_button_22.jpg';" onmouseout="this.src='img/login_button_11.jpg';" />