2015-06-14 79 views
0

我的目标是将一个元素悬停在网页上,在这种情况下是一个li标签,导致主图像与另一个元素交换。当鼠标悬停在li标签上时,备用图像将可见。备用图像在鼠标离开li标签后的n秒内保持可见。直到备用图像在n秒后交换回主图像时,才会再次触发初始悬停操作。如何避免与计时器的鼠标事件冲突

我到目前为止的搜索引导我到: Detect IF hovering over element with jQuery。 我从Meligy 分叉的的jsfiddle以及与此想出了:

var $sample = $("#sample"); 
var $main = $("#main"); 
var $alt = $("#alt"); 

$alt.hide(); 

setInterval(function() { 
    if ($sample.is(":hover")) { 
     $main.hide(); 
     $alt.show(); 
    } else { 
     setInterval(function(){ 
      $alt.hide(); 
      $main.show(); 
     },3000); 
    } 
}, 200); 

此外,jQuery on hover animation fires multiple times 和使用FC的的jsfiddle想出了这恰好是惊人地接近。

var $hover = $("#hover"); 
var $main = $("#main"); 
var $alt = $("#alt"); 

$alt.hide(); 

$hover.hover(

function() { 
    $alt.stop(true, true).show(); 
    $main.stop(true, true).hide(); 
}, 

function() { 
    $main.stop(true, true).show(2000); 
    $alt.stop(true, true).hide(2000); 
}); 

到目前为止,我最近的事情低于 但也有少数徘徊后的图像扑来回失控。

var $hover = $("#hover"); 
var $main = $("#main"); 
var $alt = $("#alt"); 

$alt.hide(); 


$hover.hover(function() { 
    if ($main.is(":visible")) { 
     $main.hide(); 
     $alt.show(); 
    } 
}, function() { 
    setInterval(function() { 

     // Also attempted $main.is(":hidden") 

     if ($main.not(":visible")){ 
      $alt.hide(); 
      $main.show(); 
     } 
    }, 3000); 
}); 

谢谢大家。

+0

通讯jsfiddles: FIRST --https://jsfiddle.net/dsbarnes/89jd73kx/2/ - SECOND - https://jsfiddle.net/dsbarnes/g66jfwfj/1/ - THIRD - - https://jsfiddle.net/dsbarnes/m18voLeL/3/ 总得有10代表超过2链接... – Snipe

回答

0

使用超时来避免此行为。原因是,无论悬停如何,间隔(超时)也会触发。如果您离开/重新输入元素,则必须取消正在运行的超时/间隔。我对您的代码进行一些编辑用于测试目的:

var timer = null; 

$hover.on('mouseenter', function() { 
    if (window.timer != null) 
     clearTimeout(window.timer); 

     $main.hide(); 
     $alt.show(); 
}); 

$hover.on('mouseout', function() { 
    window.timer = setTimeout(function() { 
     // Also attempted $main.is(":hidden") 
     $alt.hide(); 
     $main.show(); 
    }, 3000); 
}); 

更新小提琴:https://jsfiddle.net/m18voLeL/5/

+0

非常感谢 - 不会想到我自己。干杯。 – Snipe