Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 横向滚动

作者:冷言寡语   发布日期:2026-07-03   浏览:55

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>横向滚动示例</title>
    <style>
        .scroll-container {
            display: flex;
            overflow-x: auto; /* 允许横向滚动 */
            white-space: nowrap; /* 防止换行 */
        }
        .scroll-item {
            width: 200px;
            height: 100px;
            margin-right: 10px;
            background-color: lightblue;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="scroll-container">
        <div class="scroll-item">Item 1</div>
        <div class="scroll-item">Item 2</div>
        <div class="scroll-item">Item 3</div>
        <div class="scroll-item">Item 4</div>
        <div class="scroll-item">Item 5</div>
        <div class="scroll-item">Item 6</div>
    </div>

    <script>
        // 使用 JavaScript 控制滚动(可选)
        const scrollContainer = document.querySelector('.scroll-container');

        // 示例:自动滚动到指定位置
        function scrollToItem(index) {
            const item = scrollContainer.children[index];
            if (item) {
                item.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });
            }
        }

        // 模拟点击按钮滚动到第三个元素
        setTimeout(() => scrollToItem(2), 2000); // 2秒后滚动到第三个元素
    </script>
</body>
</html>

解释说明:

  1. HTML 结构:

    • scroll-container 是一个包含多个 scroll-item 的容器。
    • 每个 scroll-item 是一个宽度为 200px 的块,用于展示内容。
  2. CSS 样式:

    • display: flexoverflow-x: auto 使得容器可以横向滚动。
    • white-space: nowrap 确保子元素不会换行,保持在一行内。
  3. JavaScript:

    • 使用 scrollIntoView 方法可以平滑地滚动到指定的子元素。这里通过 setTimeout 模拟了一个 2 秒后滚动到第三个元素的效果。

上一篇:js transform

下一篇:js canvas drawimage

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站