【发布时间】:2022-02-22 14:06:24
【问题描述】:
我有点击时起作用的功能
$('#test').click(function(e){
// some code
});
如何检查test 元素是否被点击或触摸?
【问题讨论】:
标签: javascript jquery
我有点击时起作用的功能
$('#test').click(function(e){
// some code
});
如何检查test 元素是否被点击或触摸?
【问题讨论】:
标签: javascript jquery
您可以同时使用一个事件,然后检测触发事件的类型:
$('#test').on('touchend click',function(e){
if(e.type=='click')
alert('click triggered');
else
alert('touch triggered');
});
希望这会有所帮助。
$('#test').on('touchend click',function(e){
if(e.type=='click')
alert('click triggered');
else
alert('touch triggered');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">TEST</button>
【讨论】:
由于我需要一个普通的 JS 解决方案,并且这是在 Google 中出现的第一个结果,我认为更多的人会发现我的发现很有用,所以我正在写这个答案。
在寻找解决这个问题的方法时,我在Medium comment(谁会想到)中找到了这段代码,所以我封装了一个函数,对我来说就像一个魅力:
function isTouchScreen() {
return window.matchMedia('(hover: none)').matches;
}
在您的网站中实施之前,您可能想查看browser compatibility,但这对我来说很好。
【讨论】:
modern browsers 的解决方案:
$('#test').click(function(e){
if (e.pointerType === "mouse") {
// clicked with mouse
} else {
// probably touch
}
});
该解决方案本身基于 vanilla JavaScript,但也应与 jQuery 一起使用,如此处编码。
【讨论】:
正如@udoG 所指出的,解决方案是使用pointerType。
如果您使用的是jQuery:
$(selector).click(e => {
if (e.pointerType === "mouse") {} // mouse event
else {} // touch event
});
如果您使用的是vanilla JS:
element.addEventListener('click', e => {
if (e.pointerType === "mouse") {} // mouse event
else {} // touch event
});
如果您使用React,则该事件将围绕合成事件进行包装。要访问pointerType,您必须使用反应事件的nativeEvent。这是您需要考虑的内容(尤其是在使用 Typescript 时)。如果事件是由鼠标触发的,原生事件是MouseEvent的实例,它没有pointerType,所以,首先你需要检查原生事件的类型,它也会处理TS中的打字问题
<div
onClick={e => {
if (e.nativeEvent instanceof PointerEvent && e.nativeEvent.pointerType === 'touch') {} // Touch Event
else {} // Mouse Event
}}
></div>
专业提示:如果您想在开发中测试触摸事件,请在this 之后使用 Chrome。请注意,Safari 有一个响应模式,可以模拟 iPhone 和 iPad 的框架。但是,即使您处于响应式设计模式并选择了 iPhone 或 iPad,Safari 也会始终注册鼠标事件。
【讨论】: