web-dev-qa-db-ja.com

mediafire.comのようにマウスホイールをセクションにスクロールさせる方法

このウェブサイトのホームページに出くわしました http://www.mediafire.com/ 、マウスホイールを回すと、ページの位置自体が自動的にページの次のセクションに移動します。私はそれがどのように行われたかを知りたいです。誰かがこれで私を助けることができますか?前もって感謝します。

よろしく、アスウィン

7
winnyboy5

このタイプのアニメーションは、特にjQueryを初めて使用する人にはおそらく取り入れにくいと思います。これには、スクロール、マウスホイールイベントのキャッチ、アニメーションの遅延、そして何よりも、クロスブラウザやモバイルブラウザのスワイプおよびタッチイベントで正しく機能させることが含まれます。しっかりと理解していない場合は、プラグインを使用することをお勧めします。これらの2つが最適です: 1ページのスクロール および フルページ

クロスブラウザでこれを行う方法の基本的な方法のみを示します。モバイルで正しく機能させたい場合は、自分の役割を果たし、スワイプイベントとタッチイベントを追加する必要があります。 :)

//Set each section's height equals to the window height
$('section').height($(window).height());
/*set the class 'active' to the first element 
 this will serve as our indicator*/
$('section').first().addClass('active');

/* handle the mousewheel event together with 
 DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
    e.preventDefault();//prevent the default mousewheel scrolling
    var active = $('section.active');
    //get the delta to determine the mousewheel scrol UP and DOWN
    var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;

    //if the delta value is negative, the user is scrolling down
    if (delta < 0) {
        //mousewheel down handler
        next = active.next();
        //check if the next section exist and animate the anchoring
        if (next.length) {
           /*setTimeout is here to prevent the scrolling animation
            to jump to the topmost or bottom when 
            the user scrolled very fast.*/
            var timer = setTimeout(function () {
                /* animate the scrollTop by passing 
                the elements offset top value */
                $('body, html').animate({
                    scrollTop: next.offset().top
                }, 'slow');

                // move the indicator 'active' class
                next.addClass('active')
                    .siblings().removeClass('active');

                clearTimeout(timer);
            }, 800);
        }

    } else {
        //mousewheel up handler
        /*similar logic to the mousewheel down handler 
        except that we are animate the anchoring 
        to the previous sibling element*/
        prev = active.prev();

        if (prev.length) {
            var timer = setTimeout(function () {
                $('body, html').animate({
                    scrollTop: prev.offset().top
                }, 'slow');

                prev.addClass('active')
                    .siblings().removeClass('active');

                clearTimeout(timer);
            }, 800);
        }

    }
});

これがデモです: jsfiddle.net/NGj7F/

29
Mark S