【问题标题】:Apply Delay for jQuery mouseover event Tried hoverintent but i want to do it dynamically为 jQuery mouseover 事件应用延迟尝试了 hoverintent 但我想动态地做
【发布时间】:2013-12-02 12:36:44
【问题描述】:

为 jQuery 鼠标悬停事件应用延迟尝试过 hoverintent 但我想动态执行。

jQuery(document).on('mouseover', 'span[id^=viewLCmnt_]', function() {
    function ajaxTest();
});

我想在完成第一个鼠标悬停事件之前添加延迟并且不触发其他鼠标悬停。现在事件触发得如此之快以至于看起来很奇怪。

如何在鼠标悬停事件上添加延迟或仅触发单个 ajax 函数。

这样尝试过

var delay = 1000;
var area = jQuery('span[id^=viewLCmnt_],i[id^=viewLThumb_]');
area.on( 'mouseenter', function() {
    jQuery(this).data( 'mouseIsOver', true );
});
area.on( 'mouseleave', function() {
    jQuery(this).data( 'mouseIsOver', false );
});
area.on( 'mouseover', function() {
    setTImeout( function() {
        if( area.data( 'mouseIsOver' ) ) {
            area.trigger( 'mouseoverdelay' );
        }
    }, delay );
});
area.on( 'mouseoverdelay', function() {
    lv(jQuery(this), jQuery('#site').val());
});

通过以下代码解决:

var timer;
jQuery("body").on("mouseenter", "span[id^=viewLCmnt_],i[id^=viewLThumb_]", function(){
    timer = setTimeout(function () {
        lv(jQuery(this), jQuery('#site').val());
    }, 2000);
}).on("mouseleave", "span[id^=viewLCmnt_],i[id^=viewLThumb_]", function(){
    clearTimeout(timer);
});

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:
    var delay = 1000;
    
    $( ... ).on({
        mouseenter : function() {
            var $area = $(this);
            $area.data( 'mouseIsOver', true );
            // Create a scope for async problems.
            (function( $areaRef ) {
                setTimeout( function() {
                    if( $areaRef .data( 'mouseIsOver' ) ) {
                        $areaRef .trigger( 'mouseoverdelay' );
                    }
                }, delay );
            })( $area );
        },
        mouseleave : function() {
            $(this).data( 'mouseIsOver', false );
        },
        mouseoverdelay : function() {
           // Your stuff
        }
    });
    

    PS:没有测试这个。

    【讨论】:

    • 我的选择器是动态的,例如 span[id^=viewLCmnt_].. 我已经更新了问题。
    • @GeorgeJoffinJoy 编辑了我的答案。
    • $areaRef 是做什么的?
    • 见我上面的评论。我不确定您是否会遇到此类问题,但如果您遇到了,则需要这样做。
    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2011-01-17
    • 1970-01-01
    • 2015-01-17
    相关资源
    最近更新 更多