當頁面出現上下滾動條時,頁面右下角出現回到頂部功能。web
在頁面上添加以下DIV(寫的CSS內部樣式),這個DIV功能:出現滾動條往下滑動,就顯示出來,反之隱藏。點擊DIV快速回到頂部。this
<div style="{ height: 60px; width: 50px; position: fixed; bottom: 35px; right: 15px; background-color: #f2f5f6; box-shadow: 0 0 6px rgba(0,0,0, .12); text-align: center; line-height: 60px; color: #1989fa; cursor: pointer; -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -o-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); }" v-if="btnFlag" @click="backTop" > << </div>
在加入EScript代碼.spa
<script> export default { data() { return { btnFlag: false } }, mounted () { window.addEventListener('scroll', this.scrollToTop) }, destroyed () { window.removeEventListener('scroll', this.scrollToTop) }, methods: { // 點擊圖片回到頂部方法,加計時器是爲了過渡順滑 backTop () { const that = this let timer = setInterval(() => { let ispeed = Math.floor(-that.scrollTop / 5) document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed if (that.scrollTop === 0) { clearInterval(timer) } }, 16) }, // 爲了計算距離頂部的高度,當高度大於60顯示回頂部圖標,小於60則隱藏 scrollToTop () { const that = this let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop that.scrollTop = scrollTop if (that.scrollTop > 60) { that.btnFlag = true } else { that.btnFlag = false } } } } </script>
效果圖:(滾動條在頂部,div不顯示;往下滑動滾動條,div顯示)code