setTimeout 在页面上不起作用。我找不到错误。控制台不显示任何内容。
这是我的 JQuery
var timer;
function sliderColorMain(){
$('.news-main').mouseenter(function(){
timer = setTimeout(function(){
$(this).find('.sliding-color').slideDown(500);
}, 200);
}).mouseleave(function(){
// clearTimeout(timer);
$(this).find('.sliding-color').slideUp(250);
});
}
CSS 文件:
.sliding-color{
display: none;
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 100%; /*100%*/
background-color: #2573CF;
z-index: 1;
}
这是我的 HTML 文件
<div class="news-main">
<div class="sliding-color"></div>
<a href="#">
<div class="big-image">
<img src="img/main.jpg" alt="big main image">
</div>
</div>
</div>
如果没有 setTimeout 函数,这个东西就可以工作,但唯一的问题是,如果我将鼠标悬停,然后多次将其从 .news-main div 类中离开,即使鼠标没有移动,动画也会播放.所以我添加了setTimeout,但它不起作用。其实有这个功能的动画也行不通
最佳答案
您正在丢失对 setTimeout
回调中正确的 this
的引用。您可以通过多种方式解决这个问题,但箭头函数可能是最简单的:
timer = setTimeout(() => {
$(this).find('.sliding-color').slideDown(500);
}, 200);
或者,您可以使用bind
:
timer = setTimeout(function () {
$(this).find('.sliding-color').slideDown(500);
}.bind(this), 200);
或者,保存之前的 jQuery 表达式:
var $this = $(this);
timer = setTimeout(function () {
$this.find('.sliding-color').slideDown(500);
}, 200);
关于javascript - setTimeout 不起作用(JQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48972485/