Vue3一键回到顶部/底部

04-23 阅读 0评论

效果图:

 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组件

 Vue3一键回到顶部/底部

 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;
    }
}

然后直接在页面中使用即可


免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,人围观)

还没有评论,来说两句吧...

目录[+]