JavaScript summary 4.0— Browser Object Model(BOM)

    JS review 4.0 is mainly about BOM (Browser Object Model) and offset, client, scroll family series in Web APIs

    BOM

    1. Use of window object

    window.onload window loading event:
    window.onload is a window (page) loading event, when the document content is fully loaded (including images, script files, CSS file, etc.) will trigger the event
    window.onload = function() { }
    window.addEventListener('load', function() { })
    document.addEventListener('DOMContentLoaded', function(){}):
    When the initial HTML document is fully loaded and parsed, the DOMContentLoaded event is fired without waiting for stylesheets, images, and subframes to be fully loaded, which is faster than load. If there are many pictures on the page, it will take a long time from user access to onload triggering, so it is more appropriate to use the DOMContentLoaded event

    window.onresize adjust window size event: window.addEventListener("resize",function(){});:
    As long as the window size changes in pixels, this event will be triggered, and this event can be used to complete the responsive layout
    window.innerWidth The width of the current screen

    Timer:
    setTimeout(function[, delay, arg1, arg2, ...]):
    function: is the function you want to execute after the expiration time (delay milliseconds)
    delay optional: The number of milliseconds to delay (one second is equal to 1000 milliseconds)
    arg1, ..., argN optional: additional arguments, which are passed as arguments to function once the timer expires
    Cancel the timer: clearTimeout(timeoutID)timeoutID is the variable assigned when setting the timer

    setInterval:
    Set timer: var intervalID = setInterval(func, [delay, arg1, arg2, ...]);
    Clear the timer: clearInterval( intervalID );
    Note: setInterval will call the callback function every delay time, and setTimeout can only call the callback function once to stop the timer


    2. Use of location object

    The window object provides a location property for getting or setting the URL of the window

    Attributes

    location.hash: The hash attribute of the location interface returns a USVString, including the '#' in the URL identifier and the subsequent URL fragment identifier

    <a id="myAnchor" href="/en-US/docs/Location.href#Examples">Examples</a>
    <script>
      var anchor = document.getElementById("myAnchor");
      console.log(anchor.hash); // '#Examples'
    </script>
    

    location.href: get or set the whole url
    location.search: return parameters, that is, the '?' in the URL identifier and a string of URL query parameters following it (note that the obtained string contains?)

    method

    location. assign(url):
    You can jump to the url page, this method can return to the original page, that is, record the browsing history
    location. replace(url):
    Replace the url of the current page with the given url, this method will not save the current page in the session history (session History), so when the user clicks the back button, it will not jump to the original page, that is, the browsing history will not be recorded
    location. reload(boolean):
    Refresh the current page, equivalent to pressing F5. If the value passed in the brackets is true, it will force Firefox to load page resources from the server. But in other browsers any parameters are invalid

    var btn = document. querySelector('button');
         btn. addEventListener('click', function() {
             // Record the browsing history, so the back function can be realized
             console. log(window. location);
            location.assign('https://www.google.com');
             // The browsing history is not recorded, so the back function cannot be implemented
            location.replace('https://www.google.com');
            location.reload(true); //Refresh
         })
    


    Extract the parameters of the url

    The native js method extracts the incoming url parameter and returns it in the form of an object

    function getParams(url){
     let res = {}
     //Determine whether there are request parameters in the url, and if so, extract them? back part
     let arr = url.indexOf('?') > -1 ?url.split('?')[1]:[]
     arr = arr. split('&')
     arr.forEach(v=>{
         let params = v. split('=')
         res[params[0]] = params[1]
     })
     return res
    }
    

    Get the url of the browser window directly, and use the location.search method to get the request parameters

    function geteasyly() {
         //Remove first?
         let res = {}
         //Remove the parameter?
         let params = location. search. substring(1);
        let arr = params. split('&')
          console. log(arr);
        for (let v of arr){
         res[v.split('=')[0]] = v.split('=')[1]
        }
        return res
       }
    


    3. Use of navigation object

    The navigator object contains information about the browser (including the mobile phone), which can be viewed through console.log(navigator)j. It has many attributes, the most commonly used is userAgent, which can return the value of the user-agent header , which can be used to determine which terminal the user opens the page and realize the jump

    function whichTerminal() {
     if (
       navigator.userAgent.match(
         /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i,
       )
     ) {
       // i means not to distinguish (ignore) case;
       window.location.href = ''; //Mobile phone
     } else {
       window.location.href = ''; //Computer
     }
     }
    

    4. Use of history object

    Window.history is a read-only property used to obtain a reference to the History object, which provides a history of operating browser sessions (pages accessed in the browser address bar, and pages loaded through frames in the current page) Interface Use the back(), forward() and go() methods to jump backwards and forwards in the user's history

    window.history.back():
    The back function can be realized, which has the same effect as the user clicking the browser back button
    window.history.forward():
    Jump forward, as if the user clicked the forward button
    window.history.go(parameters):
    Use the go() method to load a specific page in the session history (the relative position flag of the current page is 0), if go(1) is equivalent to forward(), and go(-1) is equivalent to back()


    Get the coordinates of the mouse event (the return value does not have a unit)

    screenX : is a read-only property of MouseEvent, returns the horizontal coordinates (offset) of the mouse in the global (screen) when the event occurs

    Note: In a multi-display environment, horizontally aligned screens will be treated as a single device, so the range of screenX values ​​will increase to the combined width of the screens

    screenY : is a read-only property of MouseEvent, returns the vertical coordinates of the mouse pointer relative to the screen when the event occurs

    pageX: read-only attribute, the returned x (horizontal) coordinate of the left edge offset relative to the entire document (ie page) (the distance of the scroll bar** will be added to the calculation)

    pageY: read-only attribute, the returned offset y (horizontal) coordinate relative to the upper edge of the entire document (ie page) (the distance of the scroll bar will be added to the calculation)

    offsetX: Relative to the x coordinate of the parent box with positioning
    offsetY: Relative to the y coordinate of the parent box with positioning
    clientX : Returns the horizontal coordinates of the mouse pointer relative to the browser effective area (excluding scroll bars) when the event is triggered
    clientY: Returns the vertical coordinates of the mouse pointer relative to the browser effective area (excluding scroll bars) when the event is triggered


    offset series

    Use the offset series related attributes to dynamically get the position (offset), size, etc. of the element

    The offset attribute is a read-only attribute, which can only be obtained but not assigned; the value obtained by the offset series does not have a unit

    Attributes

    HTMLElement.offsetParent: Returns the nearest ancestor element with positioning, if the parent has no positioning, return body
    HTMLElement.offsetTop: Returns the distance from the outer border of the current element relative to the top inner border of the nearest ancestor element with positioning
    HTMLElement.offsetLeft: Returns the distance of the left border of the current element relative to the nearest ancestor element with positioning
    HTMLElement.offsetWidth: Returns the element's layout width as an integer, including padding, border, vertical scrollbar width (if present), and content width (excluding pseudo-element widths such as::before, ::after)
    NOTE: This property rounds the value to an integer. If you need decimal values ​​use element.getBoundingClientRect()
    HTMLElement.offsetHeight: returns the height of the element in integer form, the return value includes the height of the horizontal scroll bar of the padding+border+content+ element, and does not include the height of pseudo-class elements such as :before or :after

    The difference between offset and style:
    - style.width/height returns string with units
    - The value returned by style.width/height does not include padding and border (only content)
    - style You can only get the style value in the inline style sheet (that is, the style attribute written in HTML, not the css attribute)
    - style.width/height is a readable and writable attribute that can be assigned
    In summary, if you want to change the width and height of an element, you need to use style, and if you want to get the width and height of an element, you need to use offset

    Case: Simulate login box dragging

    <script>
       //The login box id is login, and the form name id is title
       var login = document. querySelector('#login');
       var title = document. querySelector('#title');
       // 1. Press the mouse to get the offset coordinates of the mouse in the login box
       title. addEventListener('mousedown', function (e) {
         var x = e.pageX - login.offsetLeft;
         var y = e.pageY - login.offsetTop;
         //2. When the mouse moves, the coordinates of the mouse in the page minus the offset coordinates of the mouse in the login box are the left and top values of the login box
         document. addEventListener('mousemove', move);
         function move(e) {
           login.style.left = e.pageX - x + 'px';
           login.style.top = e.pageY - y + 'px';
         }
         //3. Remove the mouse event when the mouse pops up
         document. addEventListener('mouseup', function () {
           document. removeEventListener('mousemove', move);
         });
       });
    </script>
    


    client series

    Use the related properties of the cient series to obtain relevant information about the visible area of the element, and dynamically obtain the border size and element size of the element, etc.
    The attribute of client is a read-only attribute, which can only be obtained and cannot be assigned; the values ​​obtained by the client series do not have units

    Element.clientTop: Get the size of the upper border of the element
    Element.clientLeft: Get the size of the left border of the element
    Element.clientHeight: 0 for elements without defined CSS or inline layout boxes; otherwise clientHeight = content+padding, excluding horizontal scrollbar height (if present), border and margin
    Element.clientWidth: Inline elements and elements without CSS styles have a clientWidth property value of 0. Otherwise clientWidth = content+padding, excluding border, margin and vertical scrollbar width


    scroll series

    Use the related attributes of the scroll series to dynamically get the size, scrolling distance, etc. of the element (the returned value does not have a unit)

    Attributes

    Element.scrollTop : Readable and writable, returns the upper side distance of the element being rolled away, and can also set the number of pixels of vertical scrolling of the content of an element in px: element.scrollTop =50

    Element.scrollLeft : Readable and writable, returns the left distance of the element being rolled away, and can also set the number of pixels for horizontal scrolling of the content of an element: element.scrollLeft =50

    Note that if the element's content direction (direction) is rtl (right-to-left), then the scrollbar will be on the far right (where the content begins), and the scrollLeft value will be 0. At this point, when you drag the scroll bar from right to left, scrollLeft will change from 0 to negative

    Element.scrollWidth : read-only property, including content that is not visible on the screen due to overflow overflow, does not contain borders, margins or vertical scroll bars: scrollWidth=padding+content (including scrolled and invisible part) + pseudo-element width

    Element.scrollHeight : read-only property, including invisible content in the view due to overflow: scrollHeight=padding+content (including the part that is rolled away and invisible)+pseudo-element height

    Window.pageYOffset: read-only property, returns the distance of the upper side (head) of page being rolled away
    Window.scrollTo(): Scroll to a specific set of coordinates in the document

    Case 1: Return to top

     header {
        height: 250px;
        background-color: red;
        width: 1200px;
        margin: 20px auto;
      }
      main {
        height: 1200px;
        background-color: aqua;
        width: 1200px;
        margin: 20px auto;
      }
      .slider-bar {
        position: fixed;
        left: 50%;
        top: 100px;
        margin-left: 600px;
        width: 45px;
        height: 50px;
        background-color: pink;
        display: none;
      }
    
     <body>
    <div class="slider-bar">Back to top</div>
    <header>head</header>
    <main>main body</main>
    <script>
      //1. get element
      var sliderbar = document.querySelector('.slider-bar');
      var main = document.querySelector('main');
      var headTop = main.offsetTop;
      sliderbar.addEventListener('click', function () {
       window.scrollTo(0, 0);
      });
      document.addEventListener('scroll', function () {
        if (window.pageYOffset < headTop) {
          sliderbar.style.display = 'none';
        } else {
          sliderbar.style.display = 'block';
        }
      });
    </script>
    


    Case 2: Image lazy loading

    Principle: Set the src of the img tag in the page to empty or the image when loading, and give the img tag a unified custom attribute data-src to store the real src of the image. When the image is detected to appear in the visible area of the window Assign data-src to the src attribute of img to realize lazy loading of images

    <body>
    <img src="./load.gif" data-src="./run1.jpg" />
    <img src="./load.gif" data-src="./run2.jpg" />
    <img src="./load.gif" data-src="./run3.jpg" />
    <img src="./load.gif" data-src="./run4.jpg" />
    <img src="./load.gif" data-src="./run1.jpg" />
    <img src="./load.gif" data-src="./run2.jpg" />
    <script>
    // Image lazy loading function
      function lazyLoad() {
        let imgs = document. getElementsByTagName('img');
        if (!imgs. length) return;
        //Height of the visible area of ​​the page
        let viewHeight = document.documentElement.clientHeight;
        //The height of the page being rolled off
        let scrollHeight =
          document.documentElement.scrollTop || document.body.scrollTop;
        //If the offsetTop of the picture (that is, the height from the top of the document, which will include the height of the scroll bar) is less than (viewHeight+scrollHeight), the picture will start to appear in the visible area and start loading
        for (let i = 0; i < imgs. length; i++) {
          if (imgs[i].offsetTop < viewHeight + scrollHeight) {
            imgs[i].src = imgs[i].dataset.src;
          }
        }
      }
      // Execute the function of loading pictures once during initialization
      lazyLoad();
    
      //Combined with the throttling function to prevent too frequent requests when scrolling
      function throttle(fn, delay) {
        let flag = false;
        let_throttle = function () {
          if (flag) return;
          flag = true;
          setTimeout(() => {
            fn.apply(this, arguments);
            flag = false;
          }, delay);
        };
        return_throttle;
      }
      window.addEventListener('scroll', throttle(lazyLoad, 800));
    </script>
    

    At the beginning of loading, only the first picture is displayed:

    The picture that appears when the page scrolls to achieve lazy loading:

    Popular posts from this blog

    大学资料分享——广工计院各个科目实验报告、课设及期末复习资料!!

    Win10 远程计算机或设备将不接受连接

    JAVA Traffic Signal Light Course Design (Source Code + Report + Video Demonstration)

    Implementation of Ajax Interceptor