Vue中點擊按鈕回到頂部(滾動效果)


頁面滾動到一定位置時,出現回到頂部按鈕 代碼如下

HTML
<div class="footer">
    <div class="gotop" v-show="gotop" @click="toTop">Top</div>
</div>

  CSS

.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中測試通過,

直接回到頂部

 // 滾動到app所在的位置(無滾動效果),如app在頂部,即回到頂部

 document.getElementById("app").scrollIntoView();

 

 

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM