JavaScript控制页面滚动位置

这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战javascript

生产实际中产长有这样的设计:点击某横向栏的某个标签或连接,页面滚动到指定版块位置。以下图所示,为京东首页的一个设计,右侧栏列出的页面版块,随着用户点击,能够快递到达页面指定位置,从而实现快速定位。html

image.png

那么如何实现这种设计呢?java

本文介绍两种实现方式:markdown

使用scrollIntoView函数

见字知义,scrollIntoView()方法会使元素对用户可见。其官方文档连接:developer.mozilla.org/zh-CN/docs/…函数

使用实例效果:oop

d804d6c4-b009-42df-bdc3-00e96f56f88b.gif

实现代码:post

<!DOCTYPE html>
<script  type="text/javascript">
    function myscroll() {
        // console.log("dd");
        document.getElementById('e8').scrollIntoView();
    }
</script>
<body>
    <div class="fixed">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <input type="button" onclick="myscroll()" value="8" />
        <div>9</div>
        <div>10</div>
        <div>11</div>
        <div>12</div>
        <div>13</div>
        <div>14</div>
    </div>
    <div>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <div id="e8">8</div>
        <div>9</div>
        <div>10</div>
        <div>11</div>
        <div>12</div>
        <div>13</div>
        <div>14</div>
    </div>
    
</body>
<style>
    body {
        font-size: 200px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .fixed {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        position:fixed;
        top: 0;
        right: 20%;
    }
</style>
​
</html>
复制代码

放在VUE中,实现代码以下:flex

<template>
    ....
    <div ref="element" @click.native="scroll">
        
    </div>
    ....
</template>
<script>
...
    methods: {
        scroll() {
            this.$refs.element.$el.scrollIntoView()
        }
    }   
...
</script>
复制代码

使用Window.scrollTo函数

window.scrollTo函数官方文档:developer.mozilla.org/zh-CN/docs/…this

使用这个函数能够实现或平滑,或瞬时的滚动效果,且能够灵活的控制滚动距离。spa

// 设置滚动行为改成平滑的滚动
window.scrollTo({
    top: 1000,
    behavior: "smooth"
});
复制代码

近期在VUE中实现的一个例子以下所示:

elementToView(ref) {
      let y = this.$refs[ref].$el.offsetTop
      /*注释部分代码实现的是因为点击组件可能在滚动过程当中position变为fixed而引发的组件距离顶部的变化而作的动态修改*/
      // if (this.fixed || ref === 'overview') {
      //  y = y - this.tabRowHeight
      // } else {
      //  y = y - this.tabRowHeight * 2
      // }
        // 关键在这里
      window.scrollTo(0, y)
    }
复制代码

最初实现这个过程当中遇到不少问题,还好都解决了,尤为是DOM各个值的含义,检索过程当中的文章列在下面:

  1. 使人头疼的clientTop、scrollTop、offsetTop
相关文章
相关标签/搜索