以下是使用原生JavaScript实现的代码:

let timer;

const div = document.querySelector('div');

div.addEventListener('touchstart', function(e) {
  timer = setTimeout(function() {
    alert('你好');
  }, 3000);
});

div.addEventListener('touchend', function(e) {
  clearTimeout(timer);
});

在这个代码中,我们使用了一个定时器 timer 来记录长按的时间。当用户开始触摸 div 元素时,我们通过 setTimeout 方法设定一个 3 秒的定时器。如果用户在 3 秒内松开了手指,则会清除这个定时器,否则会在 3 秒后执行弹出 你好 的方法。我们还为 div 元素绑定了 touchend 事件,以便在用户松开手指时及时清除定时器,避免误触时的误操作。

使用 touchstart 给div绑定长按3秒执行 一个方法弹出你好

原文地址: http://www.cveoy.top/t/topic/b4Pn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录