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

JavaScript如何将mouseover、mouseout事件转为触摸事件适配触屏设备

适配触屏设备的修改方案

触屏设备不会触发mouseover/mouseout这类鼠标专属事件,你需要补充触摸事件的监听逻辑即可实现兼容,同时不会破坏原有桌面端的使用体验。

第一步:添加CSS规则避免触摸冲突

给容器元素添加以下样式,防止触摸操作时触发页面默认的滚动、缩放行为:

.container {
  touch-action: none;
}

第二步:修改JS逻辑补充触摸事件处理

保留原有的鼠标事件绑定,额外添加触摸相关的事件监听即可,完整修改后的JS代码如下:

const container = document.querySelector('.container')
const colors = ['#3891a6', '#fde74c', '#ec9e57', '#e4795c', '#db5461','#e3655b','#95b8d1', '#666a86', '#edafb8', '#f42272', '#2541b2', '#1768ac', '#06bee1','#003459', '#662c91', '#17a398']

const SQUARES = 621

for(let i =0; i < SQUARES ; i++){
    const square = document.createElement('div')
    square.classList.add('square')

    square.addEventListener('mouseover', ()=> setColor(square))
    square.addEventListener('mouseout', ()=> removeColor(square))

    container.appendChild(square)
}

// 新增触摸事件处理
container.addEventListener('touchstart', handleTouch, { passive: false })
container.addEventListener('touchmove', handleTouch, { passive: false })
container.addEventListener('touchend', () => {
  document.querySelectorAll('.square').forEach(square => removeColor(square))
}, { passive: false })

function handleTouch(e) {
  e.preventDefault()
  const touch = e.touches[0]
  const target = document.elementFromPoint(touch.clientX, touch.clientY)
  if(target?.classList.contains('square')) {
    setColor(target)
  }
}

function setColor(element){
    const color = getRandomColor()
    element.style.background = color
    element.style.boxShadow = `0 0 5px ${color}`
}

function removeColor(element){
    element.style.background = '#1d1d1d'
    element.style.boxShadow = '0 0 2px #000'
}

function getRandomColor(){
    return colors[Math.floor(Math.random() * colors.length)]
}

修改后,在触屏设备上手指触摸或者滑动经过方块时,就会触发和鼠标悬停一致的上色效果,手指离开屏幕后所有方块都会自动恢复默认状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:27:03