1、html代码:
定义了isBottom来判断是否到底部,点击调用toBottom(100)去底部的函数
<div v-show="!isBottom" style="position:fixed;width:40px;height:40px;display:inline-block;bottom:58px;right:100px;" > <div @click="toBottom(100)" style=" { display:inline-block; height: 100%; width:100%; background-color: #f2f5f6; box-shadow: 0 0 6px rgba(0,0,0, .12); text-align: center; line-height: 20px; color: #1989fa; font-size:16px; }" >回到底部</div> </div>
2、vue的js部分代码:<script>
import{ DATE_FORMAT, ALL}from "@/components"; export default { data() { return {
ALL,
DATE_FORMAT,
isBottom: false } }, computed:{}, created(){}, methods:{ 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); } }, scrollHandle(e) { let clientHeight = document.documentElement.clientHeight || document.body.clientHeight; let scrollHeight = document.documentElement.scrollHeight; let rollheight = scrollHeight - clientHeight; let top = e.srcElement.scrollingElement.scrollTop; // 获取页面滚动高度 if (rollheight <= top + 1) { this.isBottom = true; } else { this.isBottom = false; } } }, mounted(){ window.addEventListener("scroll", this.scrollHandle); //绑定页面滚动事件 } }; </script>