Javascript 在jquery动画之前实现一个短暂的暂停
我正在编写一个简单的jquery菜单系统,它在文本链接上显示/隐藏鼠标上的DIV 我想在幻灯片开始之前实现一个短暂的暂停,这样当鼠标滑过菜单链接时菜单就不会下降 这是我当前激活菜单的方式:Javascript 在jquery动画之前实现一个短暂的暂停,javascript,jquery,Javascript,Jquery,我正在编写一个简单的jquery菜单系统,它在文本链接上显示/隐藏鼠标上的DIV 我想在幻灯片开始之前实现一个短暂的暂停,这样当鼠标滑过菜单链接时菜单就不会下降 这是我当前激活菜单的方式: <script type="text/javascript"><!-- $('#aboutLink').mouseover(function() {$('#aboutMenu1').slideDown('fast'); $('#aboutLink').css("color", "#ff297
<script type="text/javascript"><!--
$('#aboutLink').mouseover(function() {$('#aboutMenu1').slideDown('fast');
$('#aboutLink').css("color", "#ff297b");});
--></script>
因此,实际上我需要做的是在鼠标上方,等待300毫秒,然后,如果鼠标仍在链接上方,则执行动画。我建议使用hoverIntent:
您可能想这样做:
var timeout;
$('#aboutLink').mouseover(function() {
timeout = window.setTimeout(function() {
$('#aboutMenu1').slideDown('fast');
$('#aboutLink').css("color", "#ff297b");
}, 300);
});
$('#aboutLink').mouseout(function() {
if(timeout) {
window.clearTimeout(timeout);
}
});
首先设置超时,这将在300ms后执行给定的函数,但是如果用户离开div,超时将被清除,不会发生任何事情 使用
window.setTimeout
另外,我建议使用鼠标事件mouseleave
和mouseenter
(请参阅)。省去了处理嵌套元素的麻烦
那你有
var timeoutId;
$(...).mouseleave(function (ev) {
if (timeoutId) {
window.clearTimeout(timeoutId);
}
else {
// either remove the menu or set a similar timeout for disappearance
}
});
$(...).mouseenter(function (ev) {
if (timeoutId) {
// clear pending timeouts for other menu items
window.clearTimeout(timeoutId);
}
else {
// either remove other menus or transition them out
}
timeoutId = window.setTimeout(function () {
// show menu
}, 300);
});
这样做会给您留下一个简单的逻辑,因为您总是在查看当前元素。通过清除mouseenter
上的任何超时,您不必处理其他元素
当然,你可以到处乱搞,每个菜单项都有暂停时间,让你有更好的过渡。但您必须管理更复杂的问题。即使在300毫秒的间隔内移除鼠标,也会触发此错误。@Johan-是的,我在发布后注意到了这个错误。现已修复。的副本。
var timeout;
$('#aboutLink').mouseover(function() {
timeout = window.setTimeout(function() {
$('#aboutMenu1').slideDown('fast');
$('#aboutLink').css("color", "#ff297b");
}, 300);
});
$('#aboutLink').mouseout(function() {
if(timeout) {
window.clearTimeout(timeout);
}
});
var timeoutId;
$(...).mouseleave(function (ev) {
if (timeoutId) {
window.clearTimeout(timeoutId);
}
else {
// either remove the menu or set a similar timeout for disappearance
}
});
$(...).mouseenter(function (ev) {
if (timeoutId) {
// clear pending timeouts for other menu items
window.clearTimeout(timeoutId);
}
else {
// either remove other menus or transition them out
}
timeoutId = window.setTimeout(function () {
// show menu
}, 300);
});