vue点击按钮,滚动到当前页面指定位置实现方式

1.HTML

<div class="animation">
    <ul class="ui-flex">
        <li @click="changeLoc(1)">
            Step_one
        </li>
        <li @click="changeLoc(2)">
            Step_Two
        </li>
        <li @click="changeLoc(3)">
            Step_three
        </li>
        <li @click="changeLoc(4)">
            Step_four
        </li>
        <li @click="changeLoc(5)">
            Step_five
        </li>
    </ul>

    <div class="boxs">
        <div class="box"
             id="page1">
            Step_one
        </div>
        <div class="box"
             id="page2">
            Step_Two
        </div>
        <div class="box"
             id="page3">
            Step_three
        </div>
        <div class="box"
             id="page4">
            Step_four
        </div>
        <div class="box"
             id="page5">
            Step_five
        </div>
    </div>
</div>

 2.JS

export default {
    name: "animation",
    components: {},
    data() {
        return {

        };
    },
    mounted() {
    },
    methods: {
        changeLoc(key) {
            // 获取点击的按钮对应页面的id
            var PageId = document.querySelector('#page' + key)
            // 使用平滑属性,滑动到上方获取的距离
            // 下方我只设置了top,当然 你也可以加上 left 让他横向滑动
            // widow 根据浏览器滚动条,如果你是要在某个盒子里面产生滑动,记得修改
            window.scrollTo({
                'top': PageId.offsetTop,
                'behavior': 'smooth'
            })
        }
    }
};

 3.CSS

.animation {
    position: relative;
    width: 100%;
    height: 100%;
    > ul {
        width: 100%;
        height: 30px;
        line-height: 30px;
        position: fixed;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        li {
            width: 20%;
            text-align: center;
        }
    }
    .boxs {
        margin-top: 30px;
        .box {
            width: 100%;
            height: 500px;
            border-top: 2px solid #f00;
        }
    }
}

评论