JS鼠标悬浮切换图片示例

时间:2022-04-04 20:39:16

1、头部JS

function hnShowNewsPic(num){
for(i=1;i<7;i++){
document.getElementById("hn_news_pic"+i).src = "images/normal.gif";
}
document.getElementById("hn_news_pic"+num).src = "images/active.gif";
}

2、页面HTML:

    <div class="hn_news">
<ul>
<li><img id="hn_news_pic1" src="images/active.gif" onmousemove="hnShowNewsPic(1);" /></li>
<li><img id="hn_news_pic2" src="images/normal.gif" onmousemove="hnShowNewsPic(2);"/></li>
<li><img id="hn_news_pic3" src="images/normal.gif" onmousemove="hnShowNewsPic(3);"/></li>
<li><img id="hn_news_pic4" src="images/normal.gif" onmousemove="hnShowNewsPic(4);"/></li>
<li><img id="hn_news_pic5" src="images/normal.gif" onmousemove="hnShowNewsPic(5);"/></li>
<li><img id="hn_news_pic6" src="images/normal.gif" onmousemove="hnShowNewsPic(6);"/></li>
</ul>
</div>

3、切换背景图片时的写法:

//错误写法

document.getElementById("hnTab"+num).style.backgroundImage = "images/hn_tab_hover.jpg";

//正确写法

document.getElementById("hnTab"+num).style.background = "url('images/hn_tab_hover.jpg')";

或:document.getElementById("hnTab"+num).style.backgroundImage = "url(images/hn_tab_hover.jpg)";