jquery stop() 无法正常工作

jquery stop() doesn't work properly

本文关键字:常工作 工作 stop jquery      更新时间:2023-09-26

我对产品有一些DIV,我有:

// mouseenter
$(document).on('mouseenter', '.productWrapper', function(){
    $(this).stop(true,true);
    $(this).find('.productWrapperContentVisible').animate({
        height: '100px',
        opacity: '1',   
    }, function(){
        $(this).find('.productWrapperPrice').fadeIn();  
        $(this).find('.productWrapperByCompany').fadeIn();
    }); 
});
// mouseleave
$(document).on('mouseleave', '.productWrapper', function(){
    $(this).stop(true,true);
    $(this).find('.productWrapperPrice').fadeOut('fast');
    $(this).find('.productWrapperByCompany').fadeOut('fast');
    $(this).find('.productWrapperContentVisible').animate({
        height: '40px',
        opacity: '.8',      
    });
});

并且每页大约有 20 个产品,当我使用 stop(true,true) 时,在我多次移动鼠标后,这不起作用,它们继续改变高度,有时productWrapperPrice仍然存在,而我没有鼠标在那里,它应该被隐藏..

sample: http://jsfiddle.net/gwsPB/

我的代码有什么问题?谢谢

试试这个:

// mouseenter
$(document).on('mouseenter', '.productWrapper', function () {
    $(this).find('.productWrapperContentVisible').stop(true, false).animate({
        height: '100px',
        opacity: '1'
    }, function () {
        $(this).find('.productWrapperPrice, .productWrapperByCompany').stop(true, true).fadeIn();
    });
}).on('mouseleave', '.productWrapper', function () {
    var $this = $(this);
    $this.find('.productWrapperPrice, .productWrapperByCompany').stop(true, true).fadeOut('fast');
    $this.find('.productWrapperContentVisible').stop(true, false).animate({
        height: '40px',
        opacity: '.8'
    });
});

演示

问题是:当您以足够快的速度立即输入鼠标输入和鼠标离开时,mouseenter 事件中的animate函数尚未完成。当您的调用$this.find('.productWrapperContentVisible').stop(true, true)时,动画将停止,但调用回调函数会再次显示它们

function () {
   $(this).find('.productWrapperPrice, .productWrapperByCompany')
          .stop(true, true).fadeIn();
}

通过使用 stop(true, false) ,不调用回调。

您需要

在正在动画的元素上调用stop(),在祖先元素上调用它不起作用。

// mouseenter
$(document).on('mouseenter', '.productWrapper', function () {
    $(this).find('.productWrapperContentVisible').stop(true, true).animate({
        height: '100px',
        opacity: '1'
    }, function () {
        $(this).find('.productWrapperPrice, .productWrapperByCompany').stop(true, true).fadeIn();
    });
}).on('mouseleave', '.productWrapper', function () {
    var $this = $(this);
    $this.find('.productWrapperPrice, .productWrapperByCompany').stop(true, true).fadeOut('fast');
    $this.find('.productWrapperContentVisible').stop(true, true).animate({
        height: '40px',
        opacity: '.8'
    });
});