如何使用纯 JS 捕获用户的“点击”事件?不幸的是,我不能使用任何库。
问问题
63262 次
4 回答
43
该click
事件在鼠标单击和触摸单击时触发。
touchstart
触摸屏幕时触发该事件。
touchend
触摸结束时触发该事件。如果阻止默认操作,click
则不会触发事件。
于 2012-11-13T09:41:40.577 回答
7
There are touchstart
, touchend
and other events. You can add event listeners for them in this way:
var el = document.getElementById('test');
el.addEventListener('touchstart', touchHandler);
More information about native DOM events you can find on MDN webstite.
于 2012-11-13T09:43:06.787 回答
6
这不是我的代码,但我不记得我从哪里得到它,使用成功。它使用 jQuery,但没有用于点击处理本身的额外库或插件。
$.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 的项目,因此可能需要调整以同时适用于台式机和平板电脑。
于 2012-11-13T09:39:01.417 回答
2
我自己写了一个小脚本。它不在纯 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
}
});
于 2017-03-22T13:10:31.713 回答