Js listens to the scroll bar event so that the content of a label is always in the same position.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.