5

基本上,我有这个带有左右箭头按钮的图像。这张图片,默认是我从一些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">');
    }
});
4

2 回答 2

16

好吧,您可以使用该mousedown事件来启动一个显示 gif 帧的函数:http: //api.jquery.com/mousedown/,然后为mouseup将停止该函数的事件添加另一个事件处理程序。例如,该函数可以setInterval()mousedown-event 中调用,并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);
});
于 2013-05-23T06:45:45.690 回答
4

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

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

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

于 2014-02-07T13:05:00.583 回答