0

animatejQueryを使用してページを上にスクロールするコード ブロックがありますが、使いやすさを向上させるために、ユーザーが何らかの方法でスクロール モーションを妨害した場合 (たとえば、スクロール ホイール、スクロールバーをつかむなど)、モーションはすぐに停止します。 .

私は 1 週間前にここで質問をしましたが、何人かのテスターが親切にコードを試したところ、Gecko ベースのブラウザーでは動作しないと報告されました。

これは私がこれまでに持っているコードです:

$(document).ready(function() {
    // scroll to top: check if user / animate is scrolling
    var scrollAnimating = false;

    jQuery.fx.step.scrollTop = function(E) {
        scrollAnimating = true;
        E.elem.scrollTop = E.now;
        scrollAnimating = false;
    };

    // go to top (on click)
    $('#gototop').click(function() {
        $(this).fadeOut(100,function() {
            $(this).css({backgroundColor: '#CCC'}).html('Going... (scroll to stop)').fadeIn(100, function() {
                $('html,body').animate({scrollTop:0},3000);
            })
        });

        $(window).scroll(function() {
            if (!scrollAnimating) {
                $('html,body').stop();
                $('#gototop').html('Go to top');
            };
        });

        resetNames();

        return false;
    });

    function resetNames() {
        setTimeout(function() {
            $('#gototop').html('Go to top').css({backgroundColor: '#DDD'});
        },3000);
    }
});

基本的にクリック#gototopすると、スクロールが一番上にアニメーション化され始めます。スクロールが妨げられると、スクロール動作が停止し、テキスト#gototopがリセットされます。

このコードにはいくつかの問題があります: 一部の部分は途方もなく非効率的であり、Gecko ベースのブラウザーでは動作しません (大問題)。

どうすれば機能しますか?それを効率的にする方法についての指針はありますか?

4

2 に答える 2

0

Googleでこの質問を見つけた人のために、質問に答えたかっただけです:

ここで答えを見つけました:ユーザーのスクロールでスクロールトップのjqueryアニメーションを停止させますか?

基本的に、変数を使用して変数のスクロールを確認する代わりに'html, body'、ユーザーがスクロールを行ったときにのみアクティブになる関数を にバインドし、アニメーションを停止させます。

基本的に:

// Stop the animation if the user scrolls.
$('html, body').bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
    if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
        $('html, body').stop();
    }
});

OPのコンテキストに基づく回答:

$(document).ready(function() { 
    // go to top (on click)
    $('#gototop').click(function() {
        $(this).fadeOut(100,function() {
            $(this).css({backgroundColor: '#CCC'}).html('Going... (scroll to stop)').fadeIn(100, function() {
                $('html,body').animate({scrollTop:0},3000);
            })
        });
        return false;
    });
});
function resetNames() {
    setTimeout(function() {
        $('#gototop').html('Go to top').css({backgroundColor: '#DDD'});
    },3000);
}
// Stop the animation if the user scrolls.
$('html, body').bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
    if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
        $('html, body').stop();
        resetNames();
    }
});

注: テストされていません。これにより、おそらく他のすべてのアニメーションも停止すると思います。

于 2013-08-09T08:28:57.793 に答える