Home >Web Front-end >JS Tutorial >js listens to the scroll bar scroll event so that the content of a certain label is always at the same position_javascript skills

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
WBOYOriginal
2016-05-16 17:02:381208browse

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.
Statement:
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