回到顶部
原生 js 回到頂部插件
所謂插件,就是封裝好的函數,一些比較常用又強大的功能,就通俗稱為插件,像放大鏡、輪播圖等,各種各樣的功能,都可以封裝起來,需要用到是,調用即可??梢杂袇?#xff0c;也可以無參。
html結構
<span id="totop">回到頂部</span>css樣式
* {margin: 0;padding: 0;}body {height: 4000px;/* 為了體現效果 ,實際使用刪除 */}/* 回到頂部節點的樣式 */#totop {/* display: block; */width: 80px;height: 80px;ine-height: 80px;position: fixed;right: 20px;bottom: 100px;cursor: pointer;display: none;background: #ccc;text-align: center;}js代碼
/*調用案例:toTop('totop');totop:為回到頂部的元素id名稱使用步驟:*引入js(插件),*調用:toTop('節點的 id 名'); */function toTop(toTopId) {let totop = document.getElementById(toTopId);//控制出現或隱藏window.onscroll = function () {let scrollTop = window.scrollY; //獲取當前滾動距離// console.log(scrollTop)if (scrollTop >= 300) {totop.style.display = 'block'} else {totop.style.display = 'none'}}//定時器開啟步長,緩慢回到頂部,可要可不要let num = 180;let fuck = setInterval(function () {num -= 5;}, 1000);//點擊回到頂部totop.onclick = function () {let scrollTop = window.scrollY; //獲取當前滾動距離let timer = setInterval(function () {scrollTop -= num;if (scrollTop <= 0) {clearInterval(timer);}window.scrollTo(0, scrollTop); //回頂部}, 30);} }總結
- 上一篇: 搭建Nexus3(maven私服搭建)
- 下一篇: 汉字编码及区位码查询算法