1. 程式人生 > 實用技巧 >回到頂部|回到底部功能的實現(Vue)

回到頂部|回到底部功能的實現(Vue)

html:
<
a v-on:mouseover="changeActive($event)" v-on:mouseout="removeActive($event)" @click="backTOP" style="width: 39px;height: 39px;position: fixed;bottom: 119px;right: 3px;z-index: 999;"> <!-- style="width: 100%;height: 39px;position: absolute;bottom: 80px;z-index: 9000px;" --> <el-image
v-show="txt1" src="/static/xygIMG/上拉.png" style="width: 39px;height: 39px;"></el-image> <span v-show="!txt1" class="show-txt" style="width: 100%;height: 39px;display: block;"><font color="#889AA4">回到頂部</font></span> </a> <a v-on:mouseover="changeActive2($event)" v-on:mouseout
="removeActive2($event)" @click="toBottom" style="width: 39px;height: 39px;position: fixed;bottom: 70px;right: 3px;z-index: 999;"> <!-- position: absolute;bottom: 40px; --> <el-image v-show="txt2" src="/static/xygIMG/下拉.png" style="width: 39px;height: 39px;"></el-image> <
span v-show="!txt2" class="show-txt2" style="width: 100%;height: 39px;display: block;"><font color="#889AA4">回到底部</font></span> </a>

<script>
import Pagination from '@/components/Pagination'//分頁器


export default {
  components: {
    Pagination
  },

   data() {

     return {

       txt1: true, //回到頂部
       txt2: true, //回到底部

     }

   },

methods: {
            // 滑鼠移入加入class
            changeActive( /* $event */ ) {
                debugger
                this.txt1 = false;
                // this.$event.currentTarget.className="active";
            },
            removeActive($event) {
                debugger
                this.txt1 = true;
                // $event.currentTarget.className="";
            },
            // 滑鼠移入加入class
            changeActive2( /* $event */ ) {
                debugger
                this.txt2 = false;
                // this.$event.currentTarget.className="active";
            },
            removeActive2($event) {
                debugger
                this.txt2 = true;
                // $event.currentTarget.className="";
            },
            //點選回到頁面頂端
            backTOP(){
                    document.body.scrollTop = document.documentElement.scrollTop = 0;
                },
            //點選回到頁面底部
            toBottom(i) {
                let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                let scrollHeight = document.documentElement.scrollHeight;
                let rollheight = scrollHeight - clientHeight; //超出視窗上界的值就是底部的scrolTop的值
                document.documentElement.scrollTop += 200;
                if (document.documentElement.scrollTop + 1 <= rollheight) {//之所以+1,可以列印這兩個值的日誌就知道了,下面+1也是同理
                    var c = setTimeout(() => this.toBottom(i), 10);//呼叫setTimeout是為了“回到底部”這過程不是一瞬間
                  } else {
                    clearTimeout(c);
                }
            },
        }
</script>
<style scoped="scoped">
/* 
.show-txt { 
/* 回到頂部 */
display
: none; }

*/
</style>