如何让Javascript水平平滑滚动

问题描述 投票:0回答:1

我正在尝试让我的代码使我的 div 水平平滑滚动。目前它只是跳转到位置。谁能告诉我我做错了什么?我已经提供了我的代码和 JSFiddle 供您查看。

JSFiddle

CSS:

html {scroll-behavior: smooth;}
.container {
    width: 800px;
    margin: auto;
    border: 1px solid black;
    padding: 20px;
}
.flex {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    gap: 20px;
    justify-content: flex-start;
    align-items: flex-start;
    overflow: auto;
    scrollbar-width: none;
}
.flexItem {
    height: 100px;
    width: 150px;
    min-width: 150px;
    border-radius: 5px;
    border: 1px solid red;
    background-color: #d1d1d1;
}

HTML:

<div class="container">
    <div class="flex">
        <div class="flexItem">1</div>
        <div class="flexItem">2</div>
        <div class="flexItem">3</div>
        <div class="flexItem">4</div>
        <div class="flexItem">5</div>
        <div class="flexItem">6</div>
        <div class="flexItem">7</div>
        <div class="flexItem">8</div>
        <div class="flexItem">9</div>
        <div class="flexItem">10</div>
    </div>
    <br/>
    <button id="scrollLeft">Scroll Left</button>
    <button id="scrollRight">Scroll Right</button>
</div>

Javascript:

document.getElementById('scrollLeft').addEventListener('click', () => {
    document.getElementsByClassName('flex')[0].scrollTo(0, 0);
});

document.getElementById('scrollRight').addEventListener('click', () => {
    let w = document.getElementsByClassName('flex')[0].scrollWidth;
    document.getElementsByClassName('flex')[0].scrollTo(w, 0);
});

目前是正确的跳转到滚动条的开头和结尾,但是并不是平滑的滑动到结尾,而是一个刺耳的跳转。我尝试将

scroll-behavior: smooth
添加到 css,但这并没有改变任何东西。

javascript css scroll smooth-scrolling
1个回答
1
投票

试试这个

.flex {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    gap: 20px;
    justify-content: flex-start;
    align-items: flex-start;
    overflow: auto;
    scrollbar-width: none;
    scroll-behavior: smooth; /* New line */
}
© www.soinside.com 2019 - 2024. All rights reserved.