Vue3一键回到顶部/底部
效果图:
示例代码:
这是第一个盒子 这是第二个盒子 这是第三个盒子 这是第四个盒子 返回顶部 const totop = ref(); const scrollToTop = () => { window.scrollTo({ // top: document.documentElement.offsetHeight, //回到底部 top: 0, //回到顶部 left: 0, behavior: "smooth", //smooth 平滑;auto:瞬间 }); }; onMounted(() => { // 页面滚动窗口监听事件 window.onscroll = function () { // 获取浏览器卷去的高度 let high = document.documentElement.scrollTop || document.body.scrollTop; //兼容各浏览器 if (high >= 900) { totop.value.style.display = "block"; } else { totop.value.style.display = "none"; } }; }); .main { .box { width: 100vw; margin: 10px auto; background-color: rgb(173, 173, 173); font-size: 50px; text-align: center; line-height: 400px; } .totop { display: none; position: fixed; bottom: 100px; right: 50px; background-color: skyblue; padding: 10px; &:hover { cursor: pointer; color: #fff; } } }
回到底部:
window.scrollTo({ top: document.documentElement.offsetHeight, //回到底部 left: 0, behavior: "smooth", //smooth 平滑;auto:瞬间 });
封装BackTop.vue组件
components/BackTop.vue:
const totop = ref(); const scrollToTop = () => { window.scrollTo({ // top: document.documentElement.offsetHeight, //回到底部 top: 0, //回到顶部 left: 0, behavior: "smooth", //smooth 平滑;auto:瞬间 }); }; onMounted(() => { // 页面滚动窗口监听事件 window.onscroll = function () { // 获取浏览器卷去的高度 let high = document.documentElement.scrollTop || document.body.scrollTop; //兼容各浏览器 if (high >= 500) { totop.value.style.display = "block"; } else { totop.value.style.display = "none"; } }; }); .totop { display: none; position: fixed; bottom: 120px; right: 80px; background-color: #b0b0b0; padding: 10px; border-radius: 50%; &:hover { cursor: pointer; background-color: #00000088; } }
然后直接在页面中使用即可
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...