简体   繁体   中英

Add timer to change image on hover

So here's my code and the jsfiddle . The effects works great, only thing is I have no idea how to add a timer to it.

Eg When someone hovers over the image, it doesn't change the image instantly. You have to keep the cursor over it for 10 seconds before it will change.

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>

You could use setTimeout() function from Javascript to do your thing

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

Note that this.src may no longer work.

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

This can be achieved by setting a timeout in JavaScript.

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);
});

You also need to include an ID and remove the inline click events in your HTML, so it should be this:

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

JSFiddle

Note that in the JSFiddle, I did have to change the images so I can actually see them :)

You probably want to look at 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM