小工具知识网

当前位置: 首页 > 行业知识 > Vue3一键回到顶部/底部

行业知识

Vue3一键回到顶部/底部

2026-11-16 03:00:48 来源:互联网转载

效果图:

 

 示例代码:

      这是第一个盒子    这是第二个盒子    这是第三个盒子    这是第四个盒子    返回顶部  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;    }}

然后直接在页面中index.php/tags-602.html" >使用即可

上一篇:如何卸载未安装的下载文件

下一篇:Linux 上查看和刷新 DNS 缓存