我一直在我的 javascript 中使用“onclick”,但现在我希望它也能在 Iphone 上运行。对于支持 ontouchstart 的设备,是否有一种简单的方法可以使所有“onclick”像 ontouchstart 一样工作?
或者我是否需要将所有脚本编写两次(一个使用 onclick,一个使用 ontouchstart)? :S
注意:我不想使用 jquery 或任何其他库。
<!DOCTYPE html>
<title>li:hover dropdown menu on mobile devices</title>
<script>
window.onload = function () {
if ('ontouchstart' in window) {
// all "onclick" should work like "ontouchstart" instead
}
document.getElementById('hbs').onclick = function () {
alert('element was clicked');
}
}
</script>
<a id=id1 href=#>button</a>
最佳答案
这篇文章得到了更多的关注,所以我要添加另一个常用的、更新的技巧:
// First we check if you support touch, otherwise it's click:
let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
// Then we bind via thát event. This way we only bind one event, instead of the two as below
document.getElementById('hbs').addEventListener(touchEvent, someFunction);
// or if you use jQuery:
$('#hbs').on(touchEvent, someFunction);
let touchEvent
应该在您的 javascript 顶部被声明为失效(也不在 document.ready 中)。这样你就可以在你所有的 javascript 中使用它。这也允许简单的 (jQuery) 使用。
旧答案:
这解决了复制代码的需要(至少是最低限度)。不确定是否可以组合它们
function someFunction() {
alert('element was clicked');
}
document.getElementById('hbs').onclick = someFunction;
document.getElementById('hbs').ontouchstart= someFunction;
document.getElementById('hbs')
.addEventListener('click', someFunction)
.addEventListener('touchstart', someFunction);
关于javascript - 使 onclick 在 iphone 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914568/