vue3页面点击按钮滚动条置顶、tabs滚动监听亮显、点击锚点跳转整合

1、点击按钮滚动到页面头部

hooks文件夹>useBackTop.js

import { ref } from 'vue';

export default function useBackTop() {
    const scrollTop = ref(0);
    const backTopFlag = ref(false);
    const scrollToTop = () => {
        scrollTop.value = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        // 为了计算距离顶部的高度,当高度大于60显示回顶部图标,小于60则隐藏
        backTopFlag.value = scrollTop.value > 60;
    };
    const goBackTop = () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth',
        });
    };
    window.addEventListener('scroll', scrollToTop);
    return {
        scrollToTop,
        backTopFlag,
        goBackTop,
    };
}

页面中使用


2、tabs滚动监听亮显、点击锚点跳转

安装瞄点定位插件依赖

npm i smooth-scroll-into-view-if-needed

hooks文件夹>useBackTop.js

import { ref, onBeforeUnmount } from 'vue';
import scrollIntoView from 'smooth-scroll-into-view-if-needed';

export default function useScroll(navList) {
    const navCurrent = ref(navList[0]?.value);
    navCurrent.value = navList[0]?.value;
    const isFixed = ref(false);

    const scrollNav = (sections) => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // 滚动条偏移量
        // 导航吸顶
        const weTabs = document.querySelector('.wd-tabs').offsetTop;
        isFixed.value = scrollTop >= weTabs;
        sections.forEach((item, index) => {
            if (item.offsetTop - 100 <= scrollTop) {
                navCurrent.value = navList[index].value;
            }
        });
    };

    const navigate = (tab) => {
        navCurrent.value = tab;
        const node = document.querySelector(`.${tab}`);
        scrollIntoView(node, {
            scrollMode: 'if-needed',
            block: 'start',
            inline: 'nearest',
        });
    };

    document.onscroll = () => {
        scrollNav(document.querySelectorAll('.scroll-item'));
    };
    onBeforeUnmount(() => {
        document.onscroll = '';
    });
    return {
        isFixed,
        navCurrent,
        navigate,
        scrollNav,
    };
}

页面中使用


你可能感兴趣的:(前端,javascript,vue.js)