我希望能够在用户单击按钮时触发事件,然后按住该单击 1000 到 1500 毫秒。
是否有 jQuery 核心功能或插件可以实现这一点?
我应该自己滚动吗?我应该从哪里开始?
我希望能够在用户单击按钮时触发事件,然后按住该单击 1000 到 1500 毫秒。
是否有 jQuery 核心功能或插件可以实现这一点?
我应该自己滚动吗?我应该从哪里开始?
var timeoutId = 0;
$('#myElement').on('mousedown', function() {
    timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
    clearTimeout(timeoutId);
});
编辑:根据 AndyE 进行更正...谢谢!
编辑 2:现在对每个 gnarf 具有相同处理程序的两个事件使用绑定
空编码(但在这个小提琴上测试过)
(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }
    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }
    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);
// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})
如果有人感兴趣,我为此做了一个简单的 JQuery 插件。
据推测,您可以在 中开始setTimeout调用mousedown,然后在中取消它mouseup(如果mouseup在超时完成之前发生)。
但是,看起来有一个插件:longclick。
这是我目前的实现:
$.liveClickHold = function(selector, fn) {
    $(selector).live("mousedown", function(evt) {
        var $this = $(this).data("mousedown", true);
        setTimeout(function() {
            if ($this.data("mousedown") === true) {
                fn(evt);
            }
        }, 500);
    });
    $(selector).live("mouseup", function(evt) {
        $(this).data("mousedown", false);
    });
}