2012-02-27 24 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のバグのように見えます。それがあなたの進歩を妨げる可能性があります!

関連する問題