頁面滾動到必定位置時,出現回到頂部按鈕 代碼以下
HTML
<div class="footer"> <div class="gotop" v-show="gotop" @click="toTop">Top</div> </div>
CSSapp
.footer .gotop { text-align: center; position: fixed; right: 50px; bottom: 30px; cursor: pointer; padding: 10px; border-radius: 50%; background: white; color: #000000; }
JS
export default { data() { return { gotop: false }; }, mounted() {
// 此處true須要加上,不加滾動事件可能綁定不成功 window.addEventListener("scroll", this.handleScroll, true); }, methods: { handleScroll() {
let scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
scrolltop > 30 ? (this.gotop = true) : (this.gotop = false); }, toTop() { let top = document.documentElement.scrollTop || document.body.scrollTop; // 實現滾動效果 const timeTop = setInterval(() => { document.body.scrollTop = document.documentElement.scrollTop = top -= 50; if (top <= 0) { clearInterval(timeTop); } }, 10); } } }
谷歌,火狐,Edge中測試經過,測試
直接回到頂部this
// 滾動到app所在的位置(無滾動效果),如app在頂部,即回到頂部spa
document.getElementById("app").scrollIntoView();
code