本文介绍了使用jQuery将点击事件切换到touchstart的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用大量 $(文档).on('click',selector,...)事件处理程序的Web应用程序,我想要将所有这些切换为'touchstart'事件,但我想避免任何事件冒泡或重复。

I have a web application which uses lots of $(document).on('click', selector, ...) event handlers and I'd like to switch all of them to 'touchstart' event instead, but I want to avoid any event bubbling or duplication in any case.

我想把所有这些分成单独的JS文件,但是,有很多这些文件利用上面提到的事件监听器。

I was thinking to separate all of this into seperate JS files but, there are lots of these files utilizing the event listener mentioned above.

我对任何程序化方法感兴趣,如果有的话?

I'm interested in any programmatical way to achive this, if any?

我在考虑:

$('a, button, input').each(function() {
    $(this).on('touchstart', this.click);
});

但这可能是性能问题。

推荐答案

也许这是一个解决方案,您可以根据所用设备中实现的事件类型来决定使用哪个事件。我的方法基本上是:

Maybe it's a solution for you to decide which event to use based on what kind of events are implemented in the device used. My approach basically is:

var clickEvent;

if ('onpointerdown' in window) {
    // use 'pointerdown' if pointerEvent API is supported
    clickEvent = 'pointerdown';
    console.log('pointerEvents used');
} else if ('ontouchstart' in window) {
    // use 'touchstart' if touch device
    clickEvent = 'touchstart';
    console.log('touch device');
} else {
    // else use mouse event
    clickEvent = 'click';
    console.log('old fashioned mouse events');
}

$(document).on(clickEvent, '#testbtn', function(e) {
    $(e.target).css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testbtn"> Testbutton </button>

对我来说效果很好。

这篇关于使用jQuery将点击事件切换到touchstart的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:16