Jquery中的Mousehold事件

use*_*422 5 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">');
    }
});
Run Code Online (Sandbox Code Playgroud)

Zim*_*m84 16

那么你可以使用该mousedown事件来启动一个显示gif-frame的函数: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);
});
Run Code Online (Sandbox Code Playgroud)