移动端touchstart触发后,如何让目标元素显示在手指下方?
实现触摸时元素显示在手指下方的解决方案
要让元素在touchstart触发后立刻显示在手指下方,核心是获取触摸坐标并调整元素的绝对定位位置,具体实现如下:
核心逻辑
- 从
touchstart事件的touches集合中提取第一个触摸点的视口坐标(clientX/clientY) - 给目标元素设置绝对定位,通过
left/top属性控制位置 - 用触摸坐标减去元素宽高的一半,让元素中心对齐手指位置(避免默认左上角对齐的偏移问题)
修改后的完整代码
JavaScript
$('body').on('touchstart', '.draggable', function(evt) { evt.preventDefault(); console.log('TouchStart Fired'); // 获取触摸点坐标 const touch = evt.touches[0]; const touchX = touch.clientX; const touchY = touch.clientY; // 获取元素实际宽高(包含边框) const elemWidth = $(this).outerWidth(); const elemHeight = $(this).outerHeight(); // 应用样式并定位元素到手指下方 $(this).css({ 'border-color': '#55ba76', 'background-color': 'red', 'position': 'absolute', 'left': `${touchX - elemWidth / 2}px`, 'top': `${touchY - elemHeight / 2}px` }); }); // 如需拖拽过程中持续跟随手指,添加touchmove监听 $('body').on('touchmove', '.draggable', function(evt) { evt.preventDefault(); const touch = evt.touches[0]; const touchX = touch.clientX; const touchY = touch.clientY; const elemWidth = $(this).outerWidth(); const elemHeight = $(this).outerHeight(); $(this).css({ 'left': `${touchX - elemWidth / 2}px`, 'top': `${touchY - elemHeight / 2}px` }); });
CSS
.draggable { display: inline-block; border: 2px solid gold; position: absolute; /* 默认绝对定位,避免初始布局跳动 */ cursor: grab; }
HTML
<div class="draggable" draggable="true"> <svg viewBox="0 0 1 1" style="width: 5rem;"> <circle cx="0.5" cy="0.5" r="0.5" fill="#000" /> </svg> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
关键说明
evt.preventDefault()必须保留,防止浏览器默认的滚动、缩放行为干扰元素定位- 使用
outerWidth()/outerHeight()确保计算偏移时包含元素的边框和内边距,定位更准确 - 如果元素初始需要在文档流中,可以移除CSS默认的
position: absolute,改为在touchstart时动态添加,但可能导致页面布局短暂跳动
内容的提问来源于stack exchange,提问作者Parti
相关产品推荐
相关产品推荐

