如果在jquery javascript中再次发生事件,如何取消函数

时间:2017-11-21 16:33:46

标签: jquery

当我鼠标进入一个元素时,我想运行一个函数,当mouseout那个元素出现时,我想等待2秒钟,如果mouseenter再次运行那个元素,那么别做什么就运行另一个函数....我的代码

$(element).on('mouseover mouseout', function (event) {
    if(event.type == 'mouseenter') {
        $('.item').css('background', 'red');
    } else {
        setTimeout(function (){
           // may be here I want to wait and if mouseenter again to that element, I want the background of item to red and after 2 seconds background goes to green.

            $('.item').css('background', 'green');
        }, 2000);
    }
})

2 个答案:

答案 0 :(得分:0)

我不明白为什么你要结合事件然后检查?为什么不使用两个事件?你可以取消超时。这是你在想什么?

var myTimeout = null;

$(element).on('mouseenter', function (event) {
    clearTimeout(myTimeout);
    $('.item').css('background', 'red');
})
$(element).on('mouseleave', function (event) {
    myTimeout = setTimeout(function (){
        $('.item').css('background', 'green');
    }, 2000);
})

答案 1 :(得分:0)

setTimeout为您提供了一个ID,您可以在以后取消它。这样的事情可能有用:

$(element).on('mouseover mouseout', function (event) {
    if(event.type == 'mouseenter') {
        $('.item').css('background', 'red');
        if (element.timerId) { 
            clearTimeout(element.timerId);
            element.timerId = null;
        }
    } else {
        if (element.timerId) 
            clearTimeout(element.timerId);
        element.timerId = setTimeout(function (){
            $('.item').css('background', 'green');
            element.timerId = null;
        }, 2000);
    }
})