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

如何在触控设备上实现jQuery长按逐步加宽元素的功能?

触控设备实现按住加宽元素的方案

不用额外插件或第三方库,直接靠原生触控事件搭配现有jQuery就能实现。对应要用到的触控事件:

  • touchstart:对应鼠标的mousedown,手指碰到元素时触发
  • touchend:对应鼠标的mouseup,手指离开元素时触发
  • 还要处理touchmove的默认行为,比如页面滚动,避免干扰操作

完整代码示例

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='el' id='el'></div>

CSS

.el{position:absolute; left:0; top:0; width:50px; height:50px; background:orange; cursor:pointer;}

JavaScript

var el = $('#el');
var int;

function go_wplus(){
    let x = el.width() + 1;
    el.width(x);
}

// 保留鼠标事件,兼容非触控设备
el.on('mousedown', function(){
    int = setInterval(go_wplus, 100);
}).on('mouseup mouseleave', function(){
    clearInterval(int);
});

// 新增触控事件处理
el.on('touchstart', function(e){
    // 阻止默认行为,避免页面滚动、缩放等干扰交互
    e.preventDefault();
    int = setInterval(go_wplus, 100);
}).on('touchend touchcancel', function(){
    clearInterval(int);
}).on('touchmove', function(e){
    // 持续阻止默认行为,防止触摸移动时触发页面滚动
    e.preventDefault();
});

额外说明

  • 加上touchcancel事件监听,防止触摸被系统意外中断(比如弹出通知)时,定时器没被清除
  • 同时保留鼠标事件,让代码在电脑和触控设备上都能用
  • 调用e.preventDefault()是为了避免触控时浏览器的默认操作(比如滚动页面、选中文本)影响元素加宽的交互

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:52:56