jQuery source parsing style operation modules scrollLeft and scrollTop

Keywords: Javascript JQuery Fragment Attribute

scrollLeft and scrollTop are used to get / set scroll bars, as follows:

  • scrollLeft(val); read or set the horizontal scroll bar distance of the entire page
  • scrollTop(val); read or set the vertical scroll bar distance of the entire page

If no value of val is passed in, the scroll bar distance will be obtained. If val is set, the scroll bar distance will be set. Take scrollTop as an example, as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/1.7.1/jquery.min.js"></script>
    <style>
        *{margin:0;padding:0;}
        button{margin:1px 0;}
        div{margin:20px;width: 200px;height: 180px;position: relative;padding-top: 20px;background: #c38;}
        h1{margin:10px;color: #333;}
    </style>
</head>
<body>
    <br/>
    <p id="result">Result:<span></span></p>
    <button id="b1">Get vertical scroll bar distance</button><br/>
    <button id="b2">Back to the front page</button>
    <br/><br/>
    <script>
        $('#b1').click(()=>{                        //Get scroll bar distance
            $('span').text( $(window).scrollTop() )
        })
        $('#b2').click(()=>{                        //Set vertical scroll bar to scroll to top
            $(window).scrollTop(0)
        })
        //Here, first add a document fragment, and then add 50 p Label, last added to body At the front of the child node to simulate a scroll bar
        {
            let i=1,fragments=document.createDocumentFragment()
            while(i<=50){
                let p = document.createElement('p');
                p.innerHTML = i++;
                fragments.append(p)
            }
            document.body.insertBefore(fragments,document.body.childNodes[0])
        }
    </script>    
</body>
</html>

When we click button 1, we will get the distance of the current vertical scroll bar and add the result to span. Click button 2 to set the vertical scroll bar to scroll to the top. The effect is as follows:

writer by: Desert QQ:22969969

Many websites have a scroll to the top in the lower right corner to use this to achieve perfect compatibility with all websites, thanks to the perfect jQuery compatibility.

 

Source code analysis

The code implementation is as follows

jQuery.each( ["Left", "Top"], function( i, name ) {    //stay jQuery.fn Add.scrollLeft()and.scrollTop()Method     about scrollLeft For example, i Is 0 for scrollTop For example, i For 1
    var method = "scroll" + name;

    jQuery.fn[ method ] = function( val ) {                //Hang on the instance
        var elem, win;

        if ( val === undefined ) {                        //If no incoming val parameter
            elem = this[ 0 ];

            if ( !elem ) {                                //If there is no matching element
                return null;                                //Then return null
            }

            win = getWindow( elem );                    //Obtain window Object, if parameter elem yes window Object, return window Object, otherwise return false

            // Return the scroll offset
            return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
                jQuery.support.boxModel && win.document.documentElement[ method ] ||
                    win.document.body[ method ] :
                elem[ method ];                            //For reading window Object, document Rolling offset of objects and elements
        }
        //When executed here, it means that the settings are scrolled
        // Set the scroll offset
        return this.each(function() {                    //Traverse the matching elements and set the rolling offset of each element
            win = getWindow( this );

            if ( win ) {                                //If it is window Object, call scrollTo()Scroll to the execution location, both of which are required.
                win.scrollTo(
                    !i ? val : jQuery( win ).scrollLeft(),    //These two parameters are required
                     i ? val : jQuery( win ).scrollTop()
                );

            } else {
                this[ method ] = val;                    //Otherwise set the element's scrollLeft,scrollTop Attribute.
            }
        });
    };
});

getWindow is implemented as follows:

function getWindow( elem ) {
    return jQuery.isWindow( elem ) ?
        elem :                                         //If it is elem yes window Object, return directly elem
        elem.nodeType === 9 ?
            elem.defaultView || elem.parentWindow : //Otherwise, if elem Represents the entire document, return elem.defaultView(Namely window object),Otherwise return elem.parentWindow,If elem.parentWindow Return if no false
            false;
}

It can be found from the source code that if the scroll bar is operated, it needs to match the window or documetn object

Posted by mark123 on Mon, 25 Nov 2019 07:07:24 -0800