当用户悬停并单击它时,我正在尝试更改 div 的背景图像。我坚持限制图像仅更改为用户悬停/单击的元素。在此示例中,当一个 div 悬停/单击时,所有按钮都会发生变化。这是我试图复制的东西,它已经在 jQuery 中工作。我猜可以使用“this”,但到目前为止我尝试过的所有方法都会导致错误。
任何人告诉我为什么在 Firefox 页面加载时出现警报而不是 IE 或 Chrome 的人的奖励积分
JavaScript
var buttons = document.getElementsByTagName('div');
var i;
function iconDown(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -61px';
}
}
function iconUp(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -122px';
}
}
function iconOver(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -122px';
}
}
function iconOut(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px 0px';
}
}
function processAction() {
alert("Working!");
}
function Init () {
for (i=0; i<buttons.length; i++) {
if (document.addEventListener) { // all browsers except IE before version 9
buttons[i].addEventListener ("mousedown", iconDown, false);
buttons[i].addEventListener ("mouseup", iconUp, false);
buttons[i].addEventListener ("mouseover", iconOver, false);
buttons[i].addEventListener ("mouseout", iconOut, false);
buttons[i].addEventListener("click", processAction, false);
}
else { // IE before version 9
buttons[i].attachEvent ("onmousedown", iconDown);
buttons[i].attachEvent ("onmouseup", iconUp);
buttons[i].attachEvent ("onmouseover", iconOver);
buttons[i].attachEvent ("onmouseout", iconOut);
buttons[i].attachEvent("onclick", processAction);
}
}
}
Init();
CSS
.btn {width:100px; height:61px; float:left;}
#BackImg {background: url('images/Back.gif') no-repeat 0px 0px;}
#NextImg {background: url('images/Next.gif') no-repeat 0px 0px;}
HTML
<DIV class="btn" ID="BackImg"></DIV>
<DIV class="btn" ID="NextImg"></DIV>