我的目标是将元素悬停在网页上,在这种情况下是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 :(得分: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);
});