添加计时器以在悬停时更改图像

时间:2016-10-13 02:51:53

标签: javascript html css image

所以这是我的代码和jsfiddle。效果很好,唯一的问题是我不知道如何为它添加计时器。

E.g。当有人在图像上盘旋时,它不会立即改变图像。你必须将光标放在它上面10秒才能改变它。

HTML

<a href="https://www.google.com/"><img src="chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png" onmouseover="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-images-content.png'" onmouseout="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png'" /></a>

3 个答案:

答案 0 :(得分:2)

你可以使用Javascript中的setTimeout()函数来做你的事情

onmouseover="window.setTimeout(function(){  document.getElementById('image1').src='http://www.w3schools.com/css/img_fjords.jpg'
},1000);"

请注意,this.src可能不再有效。

https://jsfiddle.net/BoyWithSilverWings/dgvtvvj0/3/

答案 1 :(得分:1)

这可以通过在JavaScript中设置timeout来实现。

var timer;

document.getElementById('img-hover').addEventListener('mouseover', function() {
    clearTimeout(timer);
    var elem = this;
    timer = setTimeout(function() {
        elem.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-images-content.png';
    }, 1000);
});

document.getElementById('img-hover').addEventListener('mouseout', function() {
    clearTimeout(timer);
    var elem = this;
    timer = setTimeout(function() {
        elem.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png';
    }, 1000);
});

您还需要包含ID并删除HTML中的内嵌点击事件,因此应该是:

<a href="https://www.google.com/"><img id="img-hover" src="chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png"/></a>

JSFiddle

请注意,在JSFiddle中,我确实需要更改图像,以便我可以实际看到它们:)

答案 2 :(得分:0)

您可能希望查看setTimeout

<a href="https://www.google.com/">
    <img src="chromeextension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png" onmouseover="setTimeout(function () { this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-images-content.png'}, 10000)" onmouseout="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png'" />
</a>