css
* { Margin : 0 ; padding : 0 ;} / * Display area * / #content { height : 4800px ; width : 800px ; border : 1px Solid # 333 ; margin : 0 Auto ; position : relative ; background : URL (. " ./img/1.jpg ") ;} / * return to the top of the button * / #backTop { position : Absolute;right: -50px;top: 500px;height: 50px;width: 40px;border: 1px solid #333;text-align: center;line-height: 50px;cursor: pointer;display: none;}
html
<div id="content"> <div id="backTop">顶部</div> </div>
javascript
var backTop = document.getElementById ( 'backTop' ); var scrollTimer; var In Flag = to true ; document.onscroll = function () { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // compatible browser chrome = + 500 + scrollTop backTop.style.top 'PX' ; IF (scrollTop <600 ) { backTop.style.display = 'none'; // if the distance is less than the scroll bar 600 at the top, the button disappears let } the else IF (scrollTop > = 600 ) { backTop.style.display= 'Block' ; } // In order to improve the availability, back to top button triggers the middle when the wheel operation functions will also be triggered if the user has a scroll wheel operation, then we can try to stop the timer. IF (! In Flag) { the clearInterval (scrollTimer); } In Flag = to false ; } // Return top button function backTop.onclick = function () { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollTop = speed / 10; // the speed back to the top of the scroll bar is set to one-tenth of the distance from the top, scrollTimer = the setInterval ( function = scrollTop - () { scrollTop Speed; document.documentElement.scrollTop = document.body.scrollTop = scrollTop; // make the page back to the top of the IF (scrollTop <0 ) { document.documentElement.scrollTop = 0 ; clearInterval (scrollTimer); // If the scroll bar from top distance is less than 0 is set to 0, and the timer is stopped. } In Flag = to true ; }, 20 is ) }