The example in this article describes the usage of scroll event of js web page scroll bar. Share it with everyone for your reference. The specific analysis is as follows:
When doing the effect of js returning to the top, you need to monitor the scroll bar scrolling event of the web page. This event is: window.onscroll. When the onscroll event occurs, use js to get the scrollTop value of the page. When it is judged that scrollTop is a set value, "Return to Face" is displayed
js web scroll bar scroll event
<style type="text/css"> #top_div{ position:fixed; bottom:80px; right:0; display:none; } </style> <script type="text/javascript"> window.onscroll = function(){ var t = document.documentElement.scrollTop || document.body.scrollTop; var top_div = document.getElementById( "top_div" ); if( t >= 300 ) { top_div.style.display = "inline"; } else { top_div.style.display = "none"; } } </script> <a name="top">顶部<a> <div id="top_div"><a href="#top">返回顶部</a></div> <br /> <br /> <div> 这里尽量多些<br />以便页面出现滚动条,限于篇幅本文此处略去 </div>
Example syntax explanation
First define the top_div css attribute in the style tag: position:fixed;display:none; is the key
In the javascript statement, t gets the downward scrolling position of the scroll bar, || is for better compatibility considerations
When the scroll exceeds 300 (pixels), set the top_div css display property to display (inline), otherwise hide (none)
The DOCTYPE type must be set, and document.documentElement can be used to obtain the width and height of the window in IE
I hope this article will be helpful to everyone’s JavaScript programming design.