javascript - setTimeout 不起作用(JQuery)

标签 javascript jquery html

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/

相关文章:

javascript - 使用服务在 Controller 之间共享对象

javascript - 在具有两个或多个返回 promise 的方法的 Firebase Cloud Function 中返回什么?

javascript - 序列化带下划线的属性 ember-data

javascript - 通过GET请求获取YouTube播放列表的所有视频ID

php - 在 IE 中使用复选框展开/折叠 div

javascript - 为 JavaScript 代码创建循环

javascript - 如何暂时停止 title 属性显示工具提示?

jQuery 滑动动画不起作用

html - 菜单栏在窗口调整大小时推过 div 暴露其后面的区域

html - CSS容器定位