2012-02-27 2 views
0

사용자가 화면의 오른쪽을 가리키고 사용자가 화면의 왼쪽을 가리키면 왼쪽으로 스크롤 할 때 오른쪽으로 스크롤하는 간단한 목적으로 다음 스크립트를 작성했습니다 . 마우스를 같은 지점에 너무 오랫동안두면 끝까지 도달하기 전에 스크롤이 멈추는 것을 제외하고는 잘 작동합니다. 이후에 마우스를 움직이면 다시 스크롤을 시작합니다. 코드가 마우스 위치를 확인하고 그에 따라 스크롤하는 무한 타임 루프를 시작하기 때문에 왜 이런 일이 발생하는지 이해할 수 없습니다. 마치 마우스가 너무 오랫동안 비활성 상태 인 경우 마우스 위치가보고되는 것을 중지하는 것과 같습니다. 어떤 아이디어?자동 스크롤이 갑자기 멈춤

var mouseX = 0; 
var scrollX = 0; 
var timer; 
$(document).ready(function() { 
    // Record the mouse position if the mouse is moved 
    $(document).mousemove(function(e) { 
     mouseX = e.pageX; 
    }); 
    // Record the scroll position if the page is scrolled 
    $(document).scroll(function() { 
     scrollX = $(window).scrollLeft(); 
    }); 
    // Initiate the scrolling loop 
    scroll(); 
}); 

function scroll() { 
    // If the user is hovering over the right side of the window 
    if ((mouseX - scrollX) > 0.75*$(window).width()) { 
     scrollX += 1; 
     $(window).scrollLeft(scrollX); 
    } 
    // If the user is hovering over the left side of the window 
    if ((mouseX - scrollX) < (0.25*$(window).width())) { 
     scrollX -= 1; 
     $(window).scrollLeft(scrollX); 
    } 
    // Repeat in 5 ms 
    timer = window.setTimeout('scroll()', 5); 
} 

답변

1

코드에 어떤 문제가 있는지 정확히 알 수는 없지만 jQuery의 애니메이션을 사용하지 않는 이유는 무엇입니까? 자신의 글을 쓰는 것보다 더 신뢰할 수 있습니다.

//inside $(document).ready(): 

var which = 0; 
$('body').mousemove(function(e) { 
    var w_width = $(window).innerWidth(); 
    var prc = (e.pageX - $(window).scrollLeft())/w_width; 

    var next_which = prc < 0.25 ? -1 : (prc > 0.75 ? 1 : 0); 

    if (next_which == which) 
     return; 

    which = next_which; 
    $('html,body').stop(true); 
    if (which != 0) 
     $('html,body').animate({scrollLeft: (which > 0 ? $(document).innerWidth()-w_width : 0)}, 2000); 

}).mouseleave(function() { 
    $('html,body').stop(true);  
    which = 0; 
}); 
​ ​ 

fiddle

0

jQuery의 mousemove() 이벤트 때 발사 실패를 참조하십시오 e.pageX > $(window).width() (또는 그 부근). 나에게 jQuery 버그처럼 보인다. 그건 당신의 진전을 저해 할 수 있습니다!

관련 문제