ZetCode

JavaScript scrollLeft

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 element.scrollLeft 属性。此属性对于在 Web 开发中控制和监控元素的水平滚动至关重要。

基本定义

scrollLeft 属性获取或设置元素内容水平滚动的像素数。读取时,它返回元素内容从其左边缘滚动的距离。

如果元素的內容未滚动,或者元素无法滚动,则 scrollLeft 为 0。该值始终为非负值,以像素为单位。

基本的 scrollLeft 用法

此示例演示了如何读取可滚动 div 的 scrollLeft 值。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic scrollLeft</title>
    <style>
        #scrollable {
            width: 200px;
            height: 100px;
            overflow-x: scroll;
            white-space: nowrap;
        }
    </style>
</head>
<body>

<div id="scrollable">
    This is some very long content that requires horizontal scrolling to view completely.
</div>
<button onclick="showScroll()">Show Scroll Position</button>

<script>
    function showScroll() {
        const div = document.getElementById('scrollable');
        alert(`Current scroll position: ${div.scrollLeft}px`);
    }
</script>

</body>
</html>

在此基本示例中,我们有一个具有水平溢出的可滚动 div。当单击按钮时,JavaScript 代码将使用 scrollLeft 检索当前的水平滚动位置。

这展示了 scrollLeft 在监控水平滚动方面的基本用法。CSS 通过 overflow-x: scrollwhite-space: nowrap 确保 div 可滚动。

设置 scrollLeft 值

此示例显示如何使用 scrollLeft 以编程方式滚动元素。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Setting scrollLeft</title>
    <style>
        #container {
            width: 300px;
            overflow-x: scroll;
        }
        #content {
            width: 1000px;
            height: 100px;
            background: linear-gradient(to right, red, blue);
        }
    </style>
</head>
<body>

<div id="container">
    <div id="content"></div>
</div>
<button onclick="scrollRight()">Scroll Right 100px</button>

<script>
    function scrollRight() {
        const container = document.getElementById('container');
        container.scrollLeft += 100;
    }
</script>

</body>
</html>

这里我们有一个具有水平可滚动内容的容器。每次单击按钮时,按钮会将 scrollLeft 值增加 100 像素,从而实现平滑的水平滚动。

这展示了如何读取和写入 scrollLeft 以控制水平滚动位置。渐变背景有助于可视化滚动效果。

带 scrollLeft 的滚动事件

此示例演示了如何使用滚动事件跟踪 scrollLeft 的变化。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Scroll Events</title>
    <style>
        #scroller {
            width: 300px;
            height: 150px;
            overflow-x: scroll;
        }
        #long-content {
            width: 1000px;
            height: 150px;
            background-color: #f0f0f0;
        }
        #position {
            margin-top: 10px;
        }
    </style>
</head>
<body>

<div id="scroller">
    <div id="long-content">Scroll horizontally to see the position update</div>
</div>
<div id="position">Scroll position: 0px</div>

<script>
    const scroller = document.getElementById('scroller');
    const positionDisplay = document.getElementById('position');
    
    scroller.addEventListener('scroll', function() {
        positionDisplay.textContent = `Scroll position: ${this.scrollLeft}px`;
    });
</script>

</body>
</html>

在此示例中,我们将一个滚动事件监听器附加到一个可滚动 div。每当用户水平滚动时,事件处理程序就会使用当前的 scrollLeft 值更新显示。

这展示了如何实时监控水平滚动。在滚动期间,滚动事件会重复触发,从而可以动态跟踪位置。

平滑滚动动画

此示例使用 scrollLeft 创建平滑的水平滚动动画。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Smooth Scrolling</title>
    <style>
        #gallery {
            width: 400px;
            overflow-x: hidden;
            white-space: nowrap;
            border: 1px solid #ccc;
        }
        .image {
            display: inline-block;
            width: 400px;
            height: 300px;
            background-size: cover;
        }
    </style>
</head>
<body>

<div id="gallery">
    <div class="image" style="background-image: url('image1.jpg')"></div>
    <div class="image" style="background-image: url('image2.jpg')"></div>
    <div class="image" style="background-image: url('image3.jpg')"></div>
</div>
<button onclick="scrollToNext()">Next Image</button>

<script>
    function scrollToNext() {
        const gallery = document.getElementById('gallery');
        const targetScroll = gallery.scrollLeft + 400;
        const duration = 500; // milliseconds
        
        const startTime = performance.now();
        const startScroll = gallery.scrollLeft;
        
        function animateScroll(currentTime) {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            gallery.scrollLeft = startScroll + (targetScroll - startScroll) * progress;
            
            if (progress < 1) {
                requestAnimationFrame(animateScroll);
            }
        }
        
        requestAnimationFrame(animateScroll);
    }
</script>

</body>
</html>

此示例在图库中实现图像之间的平滑水平滚动。单击按钮时,它会为 scrollLeft 属性设置动画以滚动到下一张图像。

动画使用 requestAnimationFrame 以实现平滑性能。performance.now() 方法为动画计算提供精确的时间。

带 scrollLeft 的滚动快照

此示例将 scrollLeft 与 CSS Scroll Snap 结合使用,以获得更好的用户体验。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Scroll Snap</title>
    <style>
        #snap-container {
            width: 300px;
            overflow-x: auto;
            scroll-snap-type: x mandatory;
            display: flex;
        }
        .snap-item {
            flex: 0 0 300px;
            height: 200px;
            scroll-snap-align: start;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2em;
            color: white;
        }
        #controls {
            margin-top: 10px;
        }
    </style>
</head>
<body>

<div id="snap-container">
    <div class="snap-item" style="background: red;">1</div>
    <div class="snap-item" style="background: green;">2</div>
    <div class="snap-item" style="background: blue;">3</div>
</div>
<div id="controls">
    <button onclick="prevItem()">Previous</button>
    <button onclick="nextItem()">Next</button>
</div>

<script>
    const container = document.getElementById('snap-container');
    const itemWidth = 300;
    
    function nextItem() {
        container.scrollLeft += itemWidth;
    }
    
    function prevItem() {
        container.scrollLeft -= itemWidth;
    }
</script>

</body>
</html>

此示例使用 CSS Scroll Snap 创建了一个水平滚动容器。JavaScript 控制 scrollLeft 在项目之间导航,而 CSS 可确保快照到每个项目的边缘。

scrollLeft 和 Scroll Snap 的组合提供了精美的用户体验。按钮将 scrollLeft 增加或减少一个项目的确切宽度,CSS 则处理快照行为。

来源

MDN scrollLeft 文档

在本文中,我们探讨了 JavaScript 中的 element.scrollLeft 属性。此属性对于在 Web 应用程序中实现和控制水平滚动至关重要。

作者

我叫 Jan Bodnar,是一名热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 JS DOM 教程