JS- Get the sliding distance of the web page and monitor it in real time

introduce

This article mainly introduces the method of obtaining the sliding distance of the webpage through JS and monitoring it in real time. Analyze the difference between document.body.scrollTop, document.documentElement.scrollTop, and window.pageYOffset.

insert image description here

1. Obtain the sliding distance of the web page

JS method:
console.log('网页被卷去的高:', document.body.scrollTop);
console.log('网页被卷去的高:', document.documentElement.scrollTop);

console.log('网页被卷去的左:', document.body.scrollLeft);
console.log('网页被卷去的左:', document.documentElement.scrollLeft);
The reason why the value of document.body.scrollTop is always zero

The page specifies a DTD, that is, when a DOCTYPE is specified, use document.documentElement.scrollTop.

When the page has no DTD, that is, when no DOCTYPE is specified, document.body.scrollTop is used.

The difference of scrollTop/scrollLeft under each browser
IE:

For pages without a doctype declaration, use document.body.scrollTop or document.documentElement.scrollTop;

For pages with doctype declarations, use document.documentElement.scrollTop;

Chrome、Firefox:

For pages without doctype declaration, use document.body.scrollTop to get scrollTop height;

For pages with doctype declarations, use document.documentElement.scrollTop;

Safari:

Safari is quite special, it has its own function to get scrollTop: window.pageYOffset

Solution

Encapsulates a function compatible with all browsers

JS method:

//获得页面向左、向上卷动的距离
getScroll() {
    
    
  return {
    
    
        left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
        top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
    };
}

2. Add real-time monitoring

JS method:
mounted() {
    
    
  window.addEventListener('scroll', this.handleScroll);
},

methods: {
    
    
   handleScroll() {
    
    
      const scrollTop = this.getScroll().top;
      console.log(scrollTop)
   }
}

The result of the operation is as follows:

insert image description here


3. Remove real-time monitoring

JS method:
 destroyed() {
    
    
    window.removeEventListener('scroll', this.handleScroll);
  },

For more data information acquisition, see "JS-Get the width and height distance position information of screen/display, browser, web page, DOM element"

------------- The End -------------

License Agreement: For reprinting, please keep the original link and author.

Guess you like

Origin blog.csdn.net/weixin_43937466/article/details/126693101