얼렁뚱땅코드/jquery

스크롤 이벤트와 마우스휠이벤트로 풀페이지 만들기

얼렁뚱땅 디자이너 2019. 10. 10. 22:28

기본 마크업

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="/reset.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="/js/jquery.mousewheel.js"></script>
    <script src="index.js"></script>
</head>

<style>
    * {
    box-sizing: border-box
}
 
section {
    width: 100%;
    height: 100vh;
    position: relative;
}
 
section article {
    position: absolute;
    left: 50%;
    top: 50%;
  
    border: 1px solid #000;
    transform: translate(-50%, -50%);
    text-align: center;
 
}
 
section:nth-child(1) article {
    width: 1190px;
 
    height: 600px;
}
 
section:nth-child(2) article {
    width: 940px;
 
  height:500px
 
 
}
 
section:nth-child(3) article {
    width: 740px;
}
section:nth-child(3) article  img{
    width:300px;
}
section:nth-child(4) article {
    width: 1000px;
   height:500px
 
 
 
}
 
section:nth-child(1) {
    background: #e8e9eb;
}
 
section:nth-child(2) {
    background: #e2e7ea;
}
 
section:nth-child(3) {
    background: #1caed1;
}
 
section:nth-child(4) {
    background: #bce3f8;
}
 
.friends {
    display: flex;
    justify-content: space-evenly
}
 
h1 {
    position: absolute;
    left: 50px;
    top: 50px;
    z-index: 999;
}
 
article p {
    font-size: 24px;
    letter-spacing: -1px;
   opacity: 0;
   transition: 1s;
   margin-left:-500px
}
 
article h2 {
    font-size: 50px;
    letter-spacing: -1px;
    opacity: 0;
    transition: 1.5s;
}
article p.on {
    opacity: 1;
    margin-left:0px
}
 
article h2.on {
    opacity: 1;
}
article.black{color:#000}
article.white {color:#fff}
 
nav{position: fixed;
left:3%;
top:50%;
transform: translateY(-50%);
z-index: 999;
}
 
nav li a{color:#fff;font-size:20px }
nav li a:before{
    display: inline-block;
    content: "";
    width: 15px;height:15px;
background:#fff;
margin-right:10px}
nav li a.on{color:#21dc6d}
nav li:hover a{color:#21dc6d}
nav li:hover a:before{background:#21dc6d}
nav li a.on:before{background:#21dc6d}
 
 
h3{position: fixed;font-size: 100px;
left:0;top:0}
</style>

<body>
    <h1><img src="logo.png" alt=""></h1>
    <nav>
        <ul>
            <li><a href="#sect1" class="on">clova Friends</a> </li>
            <li> <a href="#sect2">clova Friends mini</a></li>
            <li> <a href="#sect3">MINIONS edition</a></li>
            <li><a href="#sect4">Doraemon edition</a> </li>
        </ul>


    </nav>
    <div class="wrap">
        <section id="sect1">
            <article class="black">
                <p>원하는 프렌즈를 선택해보세요</p>
                <h2>Clova Friends</h2>
                <ul class="friends">
                    <li><img src="img/article1-1.png" alt=""><img src="article1-2.png" alt=""></li>
                    <li><img src="img/article2-1.png" alt=""><img src="article2-2.png" alt=""></li>
                    <li><img src="img/article1-5.png" alt=""><img src="article1-6.png" alt=""></li>
                    <li><img src="img/article1-7.png" alt=""></li>
            </article>
        </section>

        <section id="sect2">
            <article class="black">
                <p>원하는 명령어를 선택하고, 프렌즈 미니의 답볍을 들어보세요</p>
                <h2>ClovaFriends mini</h2>
                <img src="img/article2-1.png" alt=""><img src="img/article2-2.png" alt="">
            </article>
        </section>
        <section id="sect3">
            <article class="white">
                <p>원하는 명령어를 선택하고, 미니언즈의 답변을 들어보세요.</p>
                <h2>MINIONS edition</h2>
                <img src="img/article3-1.png" alt="">
            </article>
        </section>
        <section id="sect4">
            <article class="white">
                <p>원하는 명령어를 선택하고, 도라에몽의 답변을 들어보세요.</p>
                <h2>Doraemon edition</h2>
                <img src="img/article4-1.png" alt="">
            </article>
        </section>

    </div>

    <h3>0</h3>
</body>

</html>

구글에 jquery-mousewheel을 검색하고 github에서 jquery.mousewheel.js을 가져온다.

https://github.com/jquery/jquery-mousewheel/blob/master/jquery.mousewheel.js

/*!
 * jQuery Mousewheel 3.1.13
 * Copyright OpenJS Foundation and other contributors
 */

( function( factory ) {
    if ( typeof define === "function" && define.amd ) {

        // AMD. Register as an anonymous module.
        define( [ "jquery" ], factory );
    } else if ( typeof exports === "object" ) {

        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {

        // Browser globals
        factory( jQuery );
    }
} )( function( $ ) {

    var toFix  = [ "wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll" ],
        toBind = ( "onwheel" in window.document || window.document.documentMode >= 9 ) ?
                    [ "wheel" ] : [ "mousewheel", "DomMouseScroll", "MozMousePixelScroll" ],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[ --i ] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: "3.1.12",

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[ --i ], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }

            // Store the line height and page height for this particular element
            $.data( this, "mousewheel-line-height", special.getLineHeight( this ) );
            $.data( this, "mousewheel-page-height", special.getPageHeight( this ) );
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[ --i ], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }

            // Clean up the data we added to the element
            $.removeData( this, "mousewheel-line-height" );
            $.removeData( this, "mousewheel-page-height" );
        },

        getLineHeight: function( elem ) {
            var $elem = $( elem ),
                $parent = $elem[ "offsetParent" in $.fn ? "offsetParent" : "parent" ]();
            if ( !$parent.length ) {
                $parent = $( "body" );
            }
            return parseInt( $parent.css( "fontSize" ), 10 ) ||
                parseInt( $elem.css( "fontSize" ), 10 ) || 16;
        },

        getPageHeight: function( elem ) {
            return $( elem ).height();
        },

        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };

    $.fn.extend( {
        mousewheel: function( fn ) {
            return fn ? this.on( "mousewheel", fn ) : this.trigger( "mousewheel" );
        },

        unmousewheel: function( fn ) {
            return this.off( "mousewheel", fn );
        }
    } );


    function handler( event ) {
        var orgEvent   = event || window.event,
            args       = slice.call( arguments, 1 ),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0;
        event = $.event.fix( orgEvent );
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if ( "detail" in orgEvent ) {
            deltaY = orgEvent.detail * -1;
        }
        if ( "wheelDelta" in orgEvent ) {
            deltaY = orgEvent.wheelDelta;
        }
        if ( "wheelDeltaY" in orgEvent ) {
            deltaY = orgEvent.wheelDeltaY;
        }
        if ( "wheelDeltaX" in orgEvent ) {
            deltaX = orgEvent.wheelDeltaX * -1;
        }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( "axis" in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( "deltaY" in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( "deltaX" in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) {
                delta  = deltaX * -1;
            }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) {
            return;
        }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data( this, "mousewheel-line-height" );
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data( this, "mousewheel-page-height" );
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs( deltaY ), Math.abs( deltaX ) );

        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas( orgEvent, absDelta ) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas( orgEvent, absDelta ) ) {

            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? "floor" : "ceil" ]( delta  / lowestDelta );
        deltaX = Math[ deltaX >= 1 ? "floor" : "ceil" ]( deltaX / lowestDelta );
        deltaY = Math[ deltaY >= 1 ? "floor" : "ceil" ]( deltaY / lowestDelta );

        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            event.offsetX = event.clientX - boundingRect.left;
            event.offsetY = event.clientY - boundingRect.top;
        }

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;

        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift( event, delta, deltaX, deltaY );

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if ( nullLowestDeltaTimeout ) {
            window.clearTimeout( nullLowestDeltaTimeout );
        }
        nullLowestDeltaTimeout = window.setTimeout( nullLowestDelta, 200 );

        return ( $.event.dispatch || $.event.handle ).apply( this, args );
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas( orgEvent, absDelta ) {

        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === "mousewheel" &&
            absDelta % 120 === 0;
    }

} );

js파일을 따로 빼서 제작했다.

$(function () {
  
    $('nav ul li a').click(function () {
      
     
        var href = $(this).attr('href')
 
      
        var top = $(href).offset().top
        console.log(href, top)
       
        $('html,body').animate({
            'scrollTop': top
        })
 
    })
    var h=0
    $(window).scroll(function () {
     
        var scrT = parseInt($(this).scrollTop())
   
        $('h3').text(scrT)
      h=$(window).height()
       
       $(window).resize(function(){
        h=$(window).height()
    
        })
     console.log(h)
 
        // if(scrT>=0 && scrT<h*1){
        //     $('nav ul li a').removeClass('on')
      
        //     $('nav ul li').eq(0).find('a').addClass('on')
        // }else if(scrT>h*1 && scrT<h*2 ){
        //     $('nav ul li a').removeClass('on')
      
        //     $('nav ul li').eq(1).find('a').addClass('on')  
        // }else if(scrT>=h*2&& scrT<h* 3 ){
        //     $('nav ul li a').removeClass('on')
      
        //     $('nav ul li').eq(2).find('a').addClass('on')  
        // }else if(scrT>=h*3 && scrT<h*4 ){
        //     $('nav ul li a').removeClass('on')
      
        //     $('nav ul li').eq(3).find('a').addClass('on')  
        // }
  
        // for(var i=0;i<=4;i++){
        //     if(scrT>=h*i && scrT<h*(i+1) ){
        //         $('nav ul li a').removeClass('on')
              
        //         $('nav ul li').eq(i).find('a').addClass('on')  
        //     }    
        // }
 
        $('section').each(function(i){
                var secTop=$(this).offset().top
                console.log(i,secTop)
 
                if(secTop<=scrT){
                    $('nav ul li a').removeClass('on')
                    $('nav ul li').eq(i).find('a').addClass('on')  
               
                $('article p').removeClass('on')
                $(this).find('article p').addClass('on')
                $('article h2').removeClass('on')
                $(this).find('article h2').addClass('on')
            
            }
        })
 
 
 
    })//scroll
 
 
 
    $('section').mousewheel(function (e, delta) {
  
        if (delta > 0) {
       
            var prev=  $(this).prev().offset().top
            $('html,body').animate({
              'scrollTop': prev
          })
      
        } else if (delta < 0) {
           
          var next=  $(this).next().offset().top
          $('html,body').animate({
            'scrollTop': next
        })
        }
 
    })//mousewheel
 
 
})

이미지파일

img.zip
0.28MB