Home > Web Front-end > JS Tutorial > body text

js listens to the scroll bar scroll event so that the content of a certain label is always at the same position_javascript skills

WBOY
Release: 2016-05-16 17:02:38
Original
1203 people have browsed it

Little knowledge point, without further ado, just go to the code

css:

Copy the code The code is as follows:

<style> <br>#anchor:{ <br>position:absulate; <br>top:40%; <br>left:40%; <br>width:100px; <br>height:100px; <br>background-color:red; <br>} <br></style>

js:
Copy code The code is as follows:

var auchorTop = $("#anchor").css("top"); <br>auchorTop = Number(auchorTop.substring(0, anchorTop.indexOf( "p"))); //First record the initial position of a label with id=anchor outside the listener <br>window.onscroll = function () { <br>var top = document.documentElement.scrollTop || document. body.scrollTop; <br>$("#anchor").css("top", anchorTop top "px"); <br>};


html:
Copy code The code is as follows:



You can add a scroll bar scrolling event on window.onscroll. The reason why top=document.documentElement.scrollTop||document.body.scrollTop; in the listening function is written like this is To avoid compatibility between different browsers, here I tested chrom and ff browsers. The former supports the document.body.scrollTop attribute, and the latter supports another attribute, so you can use the '||' symbol to combine these two attributes, which is compatible Different browsers. AnchorTop is the distance between the start of the target and the top of the browser. What needs to be noted here is the position of the '#anchor' tag: absulate, otherwise the top attribute value 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 at the same position.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template