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
相關文章
相關標籤/搜索