如何使用纯JS捕获用户的“tap”事件?不幸的是,我不能使用任何库。
如何使用纯JS捕获用户的“tap”事件?不幸的是,我不能使用任何库。
click
事件在鼠标点击和触摸屏幕时触发。
touchstart
事件在屏幕被触摸时触发。
touchend
事件在触摸结束时触发。如果默认操作被阻止,则不会触发click
事件。
有 touchstart
, touchend
和其他事件。您可以通过以下方式为它们添加事件监听器:
var el = document.getElementById('test');
el.addEventListener('touchstart', touchHandler);
您可以在MDN网站上找到更多关于原生DOM事件的信息。
$.event.special.tap = {
setup: function(data, namespaces) {
var $elem = $(this);
$elem.bind('touchstart', $.event.special.tap.handler)
.bind('touchmove', $.event.special.tap.handler)
.bind('touchend', $.event.special.tap.handler);
},
teardown: function(namespaces) {
var $elem = $(this);
$elem.unbind('touchstart', $.event.special.tap.handler)
.unbind('touchmove', $.event.special.tap.handler)
.unbind('touchend', $.event.special.tap.handler);
},
handler: function(event) {
event.preventDefault();
var $elem = $(this);
$elem.data(event.type, 1);
if (event.type === 'touchend' && !$elem.data('touchmove')) {
event.type = 'tap';
$.event.handle.apply(this, arguments);
} else if ($elem.data('touchend')) {
$elem.removeData('touchstart touchmove touchend');
}
}
};
$('.thumb img').bind('tap', function() {
//bind tap event to an img tag with the class thumb
}
我曾将此用于一项专门针对iPad的项目,因此可能需要进行调整才能同时适用于桌面和平板电脑。
我自己写了一个小脚本,虽然不是纯JS,但对我来说工作得很好。 它可以防止在滚动时执行脚本,这意味着脚本仅在“轻触”事件上触发。
$(element)
.on('touchstart', function () {
$(this).data('moved', '0');
})
.on('touchmove', function () {
$(this).data('moved', '1');
})
.on('touchend', function () {
if($(this).data('moved') == 0){
// HERE YOUR CODE TO EXECUTE ON TAP-EVENT
}
});
const onClickOrTap = (element, handler) => {
let touchMoveHappened = false
element.addEventListener('touchstart', () => {
// on mobile this is the 1st event that happens
touchMoveHappened = false
})
element.addEventListener('touchmove', () => {
// on mobile this might get triggered in which case the
// click or tap will get cancelled
// we'll keep a track of it
touchMoveHappened = true
})
element.addEventListener('touchend', (e) => {
// happens after touchstart, but before click
// if touch happened then we'll exit
if (touchMoveHappened) {
return
}
// calling preventDefault() will make sure the
// subsequent click will not get triggered
e.preventDefault()
// at this point we are ready to call our original handler
handler(e)
})
element.addEventListener('click', () => {
// this will only get triggered on desktop
// because we call e.preventDefault in "touchend"
handler(e)
})
}
const btn = document.querySelector('button')
onClickOrTap(btn, (e) => {
// will get triggered when the btn is clicked
// or tapped, but not when scrolling on mobile
})
declare const onClickOrTap: (element: Element, fn: (e: Event | MouseEvent<Element, globalThis.MouseEvent>) => void) => void