美文网首页
vue中使用锚点

vue中使用锚点

作者: 忘了呼吸的那只猫 | 来源:发表于2022-07-05 11:50 被阅读0次

    vue中直接使用锚点这个功能在没有引入vue-router之前是没有问题的,引入vue-router之后在未开启history模式的情况下会被视为路由的一部分。

    这个时候再想使用锚点功能就不能直接用<a href="#name"></a>这种方式了,而是使用scrollIntoView方法进行锚点的跳转。

    以下是源码:

    <!DOCTYPE html>
    <html lang="zh">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
            <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
            <script src="https://unpkg.com/vue-router@3.5.4/dist/vue-router.js"></script>
        </head>
        <body>
            <div id="app">
                <li>
                    <a href="javascript:void(0)" @click="goAnchor('tag')">跳转到目标位置</a>
                </li>
                <div style="height: 2000px;"></div>
                <a name="tag" id="tag">目标位置</a>
            </div>
    
    
            <script>
                const Foo = {
                    template: `<div>Foo</div>`,
                }
                const routes = [{
                    path: '/foo',
                    component: Foo
                }]
                const router = new VueRouter({
                    routes // (缩写) 相当于 routes: routes
                })
                const app = new Vue({
                    router,
                    data: {},
                    methods: {
                        goAnchor(e) {
                            var id = "#" + e;
                            document.querySelector(id).scrollIntoView({
                                behavior: "smooth",
                                block: "center",
                                inline: "nearest",
                            });
                        },
                    },
                }).$mount("#app")
            </script>
    
        </body>
    </html>
    

    相关文章

      网友评论

          本文标题:vue中使用锚点

          本文链接:https://www.haomeiwen.com/subject/sdlsbrtx.html