How does js listen to scroll events of a scroll bar so that the content of a label is always in the same position? The following is a good example.
Small knowledge point, not to mention nonsense, directly go to the code css: the code is as follows: <pre name = "code" class = "css"> <style> # anchor: {position: absulate; top: 40%; left: 40%; width: 100px; height: 100px; background-color: red ;}</style> </pre> <br> js: the code is as follows: <pre name = "code" class = "javascript"> var auchorTop = $ ("# anchor" ).css ("top"); auchorTop = Number (auchorTop. substring (0, anchorTop. indexOf ("p"); // first, record the initial position window of a tag with id = anchor outside the listener. onscroll = function () {va R top = document.doc umentElement. scrollTop | document. body. scrollTop; $ ("# anchor" ).css ("top", anchorTop + top + "px") ;};</pre> html: the code is as follows: <div id = "anchor"> </div> On window.onscrollable, you can scroll through the events and topic document.doc umentElement In the listener. scrollTop | document. body. scrollTop; the reason for writing this is to avoid compatibility between different browsers. Here I tested the chrom and ff browsers. The former supports document. body. the scrollTop attribute. The latter supports another attribute. Therefore, you can use the '|' symbol to combine these two attributes, which is compatible with different browsers. AnchorTop is the distance between the start of the target and the top of the browser. Note the position: absulate of the '# anchor' label. Otherwise, the top attribute value is always 0px. When the scroll bar is rolling, the top value changes. Then, add the initial top value of '# anchor' to the top value of the scroll bar to keep the content in the same position.