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

如何用JavaScript Touch Events实现Div的拉伸/调整大小?

适配触摸屏的Div拉伸调整实现方案

问题背景

已有一套通过鼠标事件实现Div垂直拉伸调整的代码,需要适配触摸屏设备的触摸事件,且不能依赖第三方库。

你尝试的触摸代码存在的问题

  • getElementsByClassName返回的是HTMLCollection集合,不是单个DOM元素,直接调用addEventListener会报错,应该用querySelector获取单个元素(和鼠标事件代码保持一致)
  • 触摸事件中,坐标需要从e.touches[0].clientY获取,而非e.clientY(触摸事件的事件对象不直接暴露clientY,需从触摸点集合中取第一个触摸点)
  • 存在拼写错误:docuemnt应该是document
  • 未在touchend时移除touchmove事件监听,会导致后续触摸操作仍然触发拉伸逻辑
  • 未阻止触摸事件的默认行为,拉伸时可能会触发页面滚动,干扰操作

修正后的完整实现代码

HTML

<div class="top-three-quarters">
</div>
<div class="bottom-quarter">
  <div class="slider">
  </div>
</div>

CSS

.top-three-quarters {
    overflow-y: auto;
    resize: vertical;
    flex: 3;
    min-height: 20%;
}

.bottom-quarter {
    flex: 1;
    max-height: 100%;
    min-height: 5%;
}

.slider {
    background-color: #dee2e6;
    cursor: row-resize;
    touch-action: none;
    user-select: none;
    height: 10px;
    margin: -5px 0;
}

JavaScript(同时支持鼠标和触摸事件)

const block = document.querySelector(".top-three-quarters");
const slider = document.querySelector(".slider");

// 通用拉伸逻辑
function startDrag(startY) {
    const handleMove = (currentY) => {
        const deltaY = currentY - startY;
        block.style.height = `${block.offsetHeight + deltaY}px`;
        startY = currentY;
    };

    // 鼠标事件处理
    const onMouseMove = (e) => handleMove(e.clientY);
    const onMouseUp = () => {
        document.removeEventListener("mousemove", onMouseMove);
        document.removeEventListener("mouseup", onMouseUp);
    };

    // 触摸事件处理
    const onTouchMove = (e) => {
        e.preventDefault();
        handleMove(e.touches[0].clientY);
    };
    const onTouchEnd = () => {
        document.removeEventListener("touchmove", onTouchMove);
        document.removeEventListener("touchend", onTouchEnd);
    };

    // 绑定事件监听
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
    document.addEventListener("touchmove", onTouchMove);
    document.addEventListener("touchend", onTouchEnd);
}

// 初始事件绑定
slider.addEventListener("mousedown", (e) => {
    e.preventDefault();
    startDrag(e.clientY);
});

slider.addEventListener("touchstart", (e) => {
    e.preventDefault();
    startDrag(e.touches[0].clientY);
});

关键技术要点

  • 触摸坐标获取:触摸事件的坐标需从e.touches[0](第一个触摸点)提取,单触摸点即可满足拉伸需求
  • 事件清理:在mouseup和touchend时必须移除对应的移动事件监听,避免内存泄漏和无效逻辑触发
  • 默认行为阻止:触摸事件中调用e.preventDefault(),防止拉伸操作触发页面滚动或缩放,保证交互体验
  • 触摸体验优化:给slider添加touch-action: none并扩大点击区域,提升触摸操作的易用性
  • 逻辑复用:抽离通用拉伸函数,减少鼠标和触摸事件的代码冗余

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:13:15