Js listens for the scroll bar to scroll events so that the contents of a label are always in the same place

  • 2020-03-30 01:29:23
  • OfStack

Small knowledge, nonsense not to say, directly on the code

<pre name="code" class="css"><style> 

<pre name="code" class="javascript">var auchorTop = $("#anchor").css("top"); 
auchorTop = Number(auchorTop.substring(0, anchorTop.indexOf("p"))); //First, the initial position of an id=anchor tag is recorded outside the listener
window.onscroll = function () { 
var top = document.documentElement.scrollTop || document.body.scrollTop; 
$("#anchor").css("top", anchorTop + top + "px"); 

<div id="anchor"></div> 

In the window. The onscroll can add the scroll bar on the scroll event, top = the document in the surveillance function. The documentElement. The scrollTop | | document. The body. The scrollTop; The reason for this is to avoid compatibility between different browsers. Here, I tested the chrom and ff browsers. The former supports the document.body.scrolltop property, while the latter supports another property, so the two properties can be combined with the '||' symbol to be compatible with different browsers. AnchorTop is the distance between the beginning of the target and the top of the browser. It is also important to note that the '#anchor 'tag' position: absulate ', otherwise the value of the top attribute is always 0px.

When the scroll bar scrolls, the top value changes, and then the initial top value of '#anchor' is added to the top value of the scroll bar to keep the content in the same position.

Related articles: