鼠标进入/离开时DIV出现/消失
我正在尝试使用jQuery进行导航。 我对jQuery很新,所以我有点卡在这里。
基本上我正在尝试做的是当我鼠标上/下testbutton1时出现并隐藏testbutton2。 我能够通过mouseenter / leave来实现这一点。
我试图添加的部分是当我将鼠标hover在testbutton2上时保持testbutton2可见,并且如果我将光标复制到testbutton1上,则保持testbutton2可见 – 所以只有淡入或淡出一次。
你会从我的代码中看到我遇到的确切内容并且可能有一个轻笑。
CSS
#testbutton1 { float:left; height:100px; width:100px; background:#69C; } #testbutton2 { float:left; height:100px; width:100px; background:#0C6; display:none; }
HTML
jQuery的
$("#testbutton1").on({ mouseenter: function() { $("#testbutton2").fadeIn(); }, mouseleave: function() { $("#testbutton2").fadeOut(); }, }); $("#testbutton2").on({ mouseenter: function() { $("#testbutton2").fadeIn(); }, mouseleave: function() { $("#testbutton2").fadeOut(); }, });
的jsfiddle
DEMO
或者你可以用纯css来做。 将两个按钮包裹在一个较大的div中,并仅在鼠标hover在较大的div上时显示第二个按钮:
#buttons:hover div { display:block; }
你可以做点什么
$("#testbutton1").on({ mouseenter: function () { $("#testbutton2").fadeIn(); }, mouseleave: function () { var $target = $("#testbutton2"); //delay the fade out to see whether the mouse is moved to the second button var timer = setTimeout(function () { $target.stop(true, true).fadeOut(); }, 200); $target.data('hoverTimer', timer); } }); $("#testbutton2").on({ mouseenter: function () { //if mouse is moved inside then clear the timer so that it will not get hidden clearTimeout($(this).data('hoverTimer')); $(this).stop(true, true).fadeIn(); }, mouseleave: function () { $(this).stop(true, true).fadeOut(); } });
演示: 小提琴
我建议使用存储的状态变量,如果你将鼠标hover在button1或button2上。
var isOver1 = false; var isOver2 = false;
然后,为mouseleave
和mouseenter
添加条件以设置隐藏或更改状态变量,例如:
mouseleave: function() { isOver1 = false; window.setTimeout( function() { if (!isOver2) { isOver2 = false; $("#testbutton2").fadeOut(); } }, 50);
超时是必要的,因为如果您离开testbutton1,则不会在同一时间进入testbutton2。 所以稍等一下就可以触发testbutton2进入事件。
这是完整的演示:
将按钮1保持为按钮2保持按钮2,留下按钮1仍保持按钮2,将任何按钮留向隐藏按钮2周围的空间。
使用此方法,您无需停止动画,因为如果不需要动画,则不会启动动画。