This article mainly provides details for everyone This article introduces JS to realize the return to top effect with animation, which has certain reference value. Interested friends can refer to
The example of this article shares with you the specific implementation of JS to realize the return to top effect with animation. Code, for your reference, the specific content is as follows
Implementation function: When scrolling to a certain height of the page, the return to the top button appears. After clicking, it returns to the top of the web page and the button is hidden.
The code is as follows. jQuery refers to Baidu CDN, so copy the entire code and run it in the browser.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>实现回到顶部功能</title> </head> <style> * { padding: 0; margin: 0; } .gotop { display: none; position: fixed; bottom: 50px; right: 50px; width: 40px; height: 40px; padding: 5px; background-color: #F00; color: #FFF; text-align: center; cursor: pointer; } </style> <script src="http://libs.baidu.com/jquery/1.8.1/jquery.min.js"></script> <body> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p>这是一段文字</p><br /><br /><br /><br /><br /><br /> <p id="goTop" class="gotop"> <p>回到</p> <p>顶部</p> </p> </body> <script> function goTop() { $(window).scroll(function() { var $scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; //兼容浏览器 if($scrollTop > 100) { //滚动高度可调 $("#goTop").show(); } else { $("#goTop").hide(); }; }) $("#goTop").on("click", function() { $("body").stop().animate({ scrollTop: 0 }); }) } goTop(); </script> </html>
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Vue component communication (detailed tutorial)
Detailed analysis of Vue Socket.io source code
The above is the detailed content of How to achieve the return to top effect in JS. For more information, please follow other related articles on the PHP Chinese website!