描述:
本文主要是讲,通过css+js实现网页中的【返回顶部】功能。
实现代码:
HTML:
- 1 <div>
- 2 <button onclick="returnTop()" id="btnTop" title="返回顶部">返回顶部</button>
- 3 </div>
CSS:
- 1 /* return top */
- 2 #btnTop {
- 3 display: none;
- 4 position: fixed;
- 5 bottom: 20px;
- 6 right: 30px;
- 7 z-index: 99;
- 8 border: none;
- 9 outline: none;
- 10 background-color: #89cff0;
- 11 color: white;
- 12 cursor: pointer;
- 13 padding: 15px;
- 14 border-radius: 10px;
- 15 }
- 16 #btnTop:hover {
- 17 background-color: #1E90FF;
- 18 }
JS:
- 1 // 当网页向下滑动 20px 出现"返回顶部" 按钮
- 2 window.onscroll = function() {
- 3 scrollFunction()
- 4 };
- 5
- 6 function scrollFunction() {
- 7 console.log(121);
- 8 if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
- 9 document.getElementById("btnTop").style.display = "block";
- 10 } else {
- 11 document.getElementById("btnTop").style.display = "none";
- 12 }
- 13 }
- 14
- 15 // 点击按钮,返回顶部
- 16 function returnTop() {
- 17 document.body.scrollTop = 0;
- 18 document.documentElement.scrollTop = 0;
- 19 }