我有一个我想要在页面加载后一秒触发的效果,然后每 3 秒触发一次(重复)。当用户将鼠标悬停在某个元素 (#hover
) 上时,效果会(暂时)暂停。当他们停止悬停在上面时,效果会在 2 秒后恢复。
我在重叠声音和动画方面遇到了很多麻烦,尤其是当我将鼠标悬停在元素上然后快速悬停时。我的代码有什么问题? ( Fiddle )
var test;
function hoverTest(arg) {
if (arg == 'stop') {
clearTimeout(test);
}
if (arg == 'start') {
playSound();
$('#hover').transition({
opacity: 0,
duration: 1000,
complete: function() {
$('#hover').transition({
opacity: 1,
duration: 1000,
complete: function() {
test = setTimeout(function() { hoverTest('start'); }, 3000);
}
});
}
});
}
}
$('#hover').hover(function() {
hoverTest('stop');
}, function() {
setTimeout(function() {
hoverTest('start');
}, 2000);
});
function playSound() {
var sound = new Audio('sound.mp3');
sound.play();
}
setTimeout(function() {
hoverTest('start');
}, 1000);
最佳答案
将其复制粘贴到文件中并运行该 html 文件。
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#hover {
width: 100px;
height: 100px;
background: red;
}
</style>
<div id="hover"></div>
<script type="text/javascript">
var interval = null;
var hoverTest = function(method){
playSound();
$("#hover").fadeOut(1000, function() {
$(this).fadeIn(1000);
});
}
var playSound =function() {
var sound = new Audio('http://www.sounddogs.com/previews/25/mp3/306470_SOUNDDOGS__an.mp3');
sound.play();
}
$(document).ready(function(){
interval = setInterval('hoverTest()',3000);
$("#hover").mouseenter(function(){
clearInterval(interval);
}).mouseleave(function(){
interval = setInterval('hoverTest()',3000);
})
})
</script>
关于javascript - setTimeout 与 jQuery.hover() 重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21228744/