我的页面中有8个img元素 -
<a href = "#"><img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/></a>
<a href = "#"><img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/></a>
在悬停时,它应该从1_1变为1_2直到1_8然后再次变为1_1。在鼠标输出时,它应显示默认图片,即1_1。像这样我有2_1,3_1到8_1。
mousehover的javascript函数是 -
function mousehover(x){
for(var i=2; i<9; i++){
x.src = x.src.replace('images/rotator/1_' + i + '.jpg');
}
}
function defaultImg(x){
x.src = x.src.replace("images/rotator/1_1.jpg");
}
不知何故,这个鼠标悬停功能不起作用。如何在鼠标输出时获取所有图像的defaultImg。我被困在这里。有什么想法吗?
答案 0 :(得分:2)
尝试以下方法。应该工作:
var timer;
var i=2;
function mousehover(x){
x.src = 'images/rotator/1_' + i + '.jpg';
i++;
timer = setTimeout(function(){mousehover(x)},2000);
}
function defaultImg(x){
i=2;
clearTimeout(timer);
x.src = "images/rotator/1_1.jpg";
}
答案 1 :(得分:1)
您可以在函数调用中传递第一个数字作为参数。
<a href = "#"><img onmouseover="mousehover(this, 1)" onmouseout="defaultImg(this, 1)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/></a>
<a href = "#"><img onmouseover="mousehover(this, 2)" onmouseout="defaultImg(this, 2)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/></a>
JavaScript将是:
var interval;
function mousehover(x, y) {
var i = 1;
interval = setInterval(function() {
i++;
if (i > 8) {
clearInterval(interval);
i = 1;
}
x.src = 'images/rotator/' + y + '_' + i + '.jpg';
}, 500);
}
function defaultImg(x, y) {
clearInterval(interval);
x.src = 'images/rotator/' + y + '_1.jpg';
}
为了获得更高的性能,我会将所有图像合并为一个大精灵,并使用背景位置进行播放,而不是每次都加载新图像。
答案 2 :(得分:0)
这些行中的某些内容应该有效:
var element = document.querySelector("#switch");
element.addEventListener('mouseover', function() {
this.src = "http://placehold.it/400x300";
});
element.addEventListener('mouseout', function() {
this.src = "http://placehold.it/200x300";
});
答案 3 :(得分:0)
你需要这样的东西:
//TIP: Insert listeners with javascript, NOT html
x.addEventListener('mouseover', function () {
var count = 1,
that = this,
timer;
timer = setInterval(function () {
if (count < 8) {
count++;
} else {
count = 1;
}
that.src = 'images/rotator/1_' + count + '.jpg';
}, 500);
function onMouseOut() {
that.src = 'images/rotator/1_1.jpg';
that.removeEventListener('mouseout', onMouseOut)
}
this.addEventListener('mouseout', onMouseOut);
});