我有这个 jquery 函数来对下拉菜单执行 slideDown 效果:
jQuery(window).ready(function(){
jQuery('.menu li').hover(function(){
jQuery(this).children('ul').delay(20).slideDown(200);
},
function(){
jQuery(this).children('ul').delay(20).slideUp(200);
});
});
我意识到每次悬停都掉线很烦人,所以我想添加一个超时功能但卡住了。我不能再使用“这个”,我猜是因为范围。现在我有以下功能,但它同时删除了 .menu li ul 和 .menu li ul ul ....我将如何再次使用“this”,或者确保只有悬停元素的子元素是掉了下来?谢谢!
jQuery(window).ready(function(){
var timeoutId;
jQuery('.menu li').hover(function() {
if (!timeoutId) {
timeoutId = window.setTimeout(function() {
timeoutId = null;
jQuery('.menu li').children('ul').delay(20).slideDown(200);
}, 500);
}
},
function () {
if (timeoutId) {
window.clearTimeout(timeoutId);
timeoutId = null;
}
else {
jQuery(this).children('ul').delay(20).slideUp(200);
}
});
});
此外,我的 CSS 如下:
#mainMenu { /*don't change width or height here. use #menurow in template.css*/
float: right;
width: 100%;
}
.menu
{
margin:0;
padding:0;
}
.menu ul{
list-style: none;
margin: 0;
padding: 0;
}
.menu > li
{
list-style:none;
float:left;
margin:0;
padding:0;
position:relative;
text-align: left;
line-height: 37px;
font-size: 13px;
}
.menu > li ul
{
margin:0;
padding:0;
width:190px;
position:absolute;
display:none;
background: #666666;
z-index: 999;
}
.menu > li ul ul
{
margin:0;
padding:0;
width:190px;
position:absolute;
display:none;
left:190px;
top:0;
z-index: 999;
}
.menu > li ul li
{
margin:0;
padding:0;
list-style:none;
position:relative;
}
.menu a {
display: block;
font-weight: bold;
text-decoration: none;
color: #fff;
margin: 0;
padding-left: 30px;
padding-right: 30px;
}
.menu li.active a {
background: #454545;
}
.menu a:hover{
color: #FBF4B6;
background: #333;
}
.menu li ul li a {
padding-left: 30px;
padding-bottom:2px;
padding-top:2px;
border-bottom: 1px solid #999;
}
.menu li.active ul li a:hover {
background: #333;
}
最佳答案
您可以使用 bind
重用 this
:
timeoutId = window.setTimeout(function() {
timeoutId = null;
jQuery(this).children('ul').delay(20).slideDown(200);
}.bind(this), 500);
或者,您可以将 this
引用保存到作用域外的变量中:
if (!timeoutId) {
var $this = $(this);
timeoutId = window.setTimeout(function() {
timeoutId = null;
$this.children('ul').delay(20).slideDown(200);
}, 500);
}
关于jQuery 下拉菜单 - setTimeout 和 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22645056/