2013-05-23 9 views
4

기본적으로 왼쪽 및 오른쪽 화살표 버튼이있는이 이미지가 있습니다. 이 이미지는 기본적으로 일부 gif에서 추출한 첫 번째 프레임이며 원래 gif에는 31 개 프레임이 포함되어 있습니다. 내 목표는 사용자가 오른쪽 화살표 단추를 클릭하면 다음 프레임을 표시하는 등의 작업입니다. 아래 코드와 같이 모든 작업이 완벽하게 작동합니다. 그러나 사용자가 마우스를 클릭하여 잡고있을 때 다음 이미지를 계속 실행하고 싶도록 일부 mousehold 이벤트를 추가해야합니다. 이것을 어떻게 할 수 있습니까? http://api.jquery.com/mousedown/을하고 그 기능을 중지합니다 mouseup 이벤트에 대한 또 다른 이벤트 처리기를 추가 :Jquery에서 마우스 홀드 이벤트

$('#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">'); 
    } 
}); 
+0

'태폴'이벤트는 어떻습니까? – Roshdy

답변

15

그럼 당신은 GIF 프레임을 표시하는 기능을 시작합니다 mousedown 이벤트를 사용할 수 있습니다. 이 함수는 mousedown -event의 setInterval()을 통해 호출 할 수 있으며 mouseup 이벤트에서 clearInterval()을 통해 중지 할 수 있습니다.

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); 
}); 
+0

mousedown과 setInterval이 함께 작동하는 방법을 보여줄 수 있습니까? – user2310422

+2

감사합니다. – user2310422

4

Zim84의 답변 또한, 나는 또한이 코드 조각을 추가해야합니다 :

는이 원리를 보여줍니다 예입니다!

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

이 사람이 버튼을 버튼 (mousedown)를 밀어 (mouseout)를 아래로 마우스를 보유하고 잎 경우, 간격이 지워 것을 돌볼 것입니다. 이 간격이 없으면이 특별한 상황에서 간격이 멈추지 않습니다.