You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端标签页滑动实现及精准平滑滚动问题求助

移动端滑动切换标签页+平滑定位实现方案

针对你现有标签页代码,我们可以通过添加触摸事件监听和优化过渡逻辑,实现移动端滑动切换标签并精准平滑定位的效果,完整代码如下:

完整代码

HTML

<div class="wrapper">
    <button class="active"> Tab 1</button>
    <button> Tab 2</button>
    <button> Tab 3</button>
    
    <div id="tab" class="tabs inliner">
        <div>
            <h2>Content 1</h2>
        </div>
        <div>
            <h2>Content 2</h2>
        </div>
        <div>
            <h2>Content 3</h2>
        </div>
    </div>
</div>

CSS

.wrapper {
    overflow: hidden;
}

.tabs {
    position: relative;
    transition: transform 0.3s ease-in-out; /* 优化过渡时长,更贴合滑动体验 */
}

.tabs> * {
    width: 100%;
    min-height: 200px; /* 给内容区加最小高度,避免滑动区域过小 */
}

.tabs[data-tab='1'] {
    transform: translateX(-100%);
}

.tabs[data-tab='2'] {
    transform: translateX(-200%);
}

.inliner {
    white-space: nowrap;
}

.inliner > * {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    font-size: 1rem;
    letter-spacing: normal;
    vertical-align: top;
    word-spacing: normal;
    white-space: normal;
}

button.active {
    background-color: #eee; /* 给激活态按钮加样式,方便区分 */
}

JavaScript

const btn = Array.from(document.getElementsByTagName('button'));
const tabContainer = document.getElementById('tab');
let currentTab = 0;
let startX = 0;
const tabCount = btn.length;
const swipeThreshold = window.innerWidth * 0.15; // 滑动触发阈值:屏幕宽度的15%

// 点击切换逻辑
btn.forEach((item, index) => {
    item.addEventListener('click', function() {
        switchTab(index);
    });
});

// 触摸事件监听
tabContainer.addEventListener('touchstart', (e) => {
    startX = e.touches[0].clientX;
});

tabContainer.addEventListener('touchend', (e) => {
    const endX = e.changedTouches[0].clientX;
    const swipeDistance = startX - endX;

    // 判断滑动方向和是否达到阈值
    if (swipeDistance > swipeThreshold && currentTab < tabCount - 1) {
        // 向左滑,切换到下一个标签
        switchTab(currentTab + 1);
    } else if (swipeDistance < -swipeThreshold && currentTab > 0) {
        // 向右滑,切换到上一个标签
        switchTab(currentTab - 1);
    }
});

// 统一切换标签的逻辑
function switchTab(targetIndex) {
    // 更新按钮激活态
    btn.forEach(item => item.classList.remove('active'));
    btn[targetIndex].classList.add('active');
    // 更新容器的data-tab属性,触发CSS过渡
    tabContainer.setAttribute('data-tab', targetIndex);
    currentTab = targetIndex;
}

关键实现说明

  • 触摸事件处理:通过touchstart记录滑动起始位置,touchend计算滑动距离,当滑动距离超过设定阈值(屏幕宽度15%)时触发标签切换,避免误触。
  • 统一切换逻辑:把点击和滑动的切换逻辑封装成switchTab函数,保证按钮状态和标签内容同步更新。
  • 平滑过渡:依靠CSS的transition: transform 0.3s ease-in-out实现滑动后的平滑定位,修改过渡时长可以调整动画快慢。
  • 精准定位:通过修改data-tab属性触发对应的transform位移,确保每次切换后标签内容精准对齐视图,不会停在中间位置。

内容的提问来源于stack exchange,提问作者CcCcSS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:15:37