Jquery中的Mousehold事件

时间:2013-05-23 06:39:37

标签: javascript jquery

基本上,我有左右箭头按钮这个图像。默认情况下,此图像是我从某个gif中提取的第一帧,原始gif包含31帧。我的目标是当用户点击右箭头按钮时,我想显示下一帧等等......一切正常,如下图所示。但是,我需要添加一些mousehold事件,以便当用户单击并按住鼠标时,我想继续触发下一个图像。我怎样才能做到这一点?

$('#arrow_right').click(function (event) {
    event.preventDefault();
    var data_id = parseInt($(this).parent().find('#inner_wrap img').attr('data-id'));

    if (data_id >= 1 && data_id <= 30) {
        data_id = data_id + 1;
        var avatar_num = $('#inner_wrap').html('<img id="avatar" data-id="' + data_id + '" src="img/avatar_test' + data_id + '.gif" width="90" height="200">');
    }
});

2 个答案:

答案 0 :(得分:16)

您可以使用mousedown事件启动显示gif-frame的函数:http://api.jquery.com/mousedown/,然后为将停止该函数的mouseup事件添加另一个事件处理程序。例如,可以通过setInterval() - 事件中的mousedown来调用该函数,并在clearInterval()事件中通过mouseup停止。

这是一个显示原则的例子:

var interval;
$(button).addEventListener('mousedown',function(e) {
    interval = setInterval(function() {
        // here goes your code that displays your image/replaces the one that is already there
    },500); // 500ms between each frame
});
$(button).addEventListener('mouseup',function(e) {
    clearInterval(interval);
});
// Thank you, Timo002, for your contribution!
// This code will stop the interval if you move your mouse away from the button while still holding it.
$(button).addEventListener('mouseout',function(e) {
    clearInterval(interval);
});

答案 1 :(得分:4)

除了Zim84的答案之外,我还应该添加这段代码!

$(button).addEventListener('mouseout',function(e) {
    clearInterval(interval);
});

如果有人按下按钮(mousedown)并按住鼠标并离开(mouseout)按钮,则会注意间隔也会被清除。没有这个,间隔不会在这种特殊情况下停止。