在iphone上进行onclick工作 [英] Make onclick work on iphone
问题描述
我一直在我的javascript中使用onclick,但现在我希望它也适用于Iphone。有没有一种简单的方法可以使所有onclick像ontouchstart一样工作,支持ontouchstart?
I have been using "onclick" in my javascript, but now I want it to work on Iphone as well. Is there a simple way to make all "onclick" to work like ontouchstart for devices that support ontouchstart?
或者我需要写两次所有脚本(一个使用onclick的脚本)和一个使用ontouchstart)? :S
Or do I need to write all script twice (one that uses onclick and one that uses ontouchstart)? :S
注意:我不想使用jquery或任何其他库。
Note: I dont want to use jquery or any other library.
<!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>
推荐答案
这篇文章得到了更多关注,所以我要去添加另一个常用的,更新的技巧:
This post got more attention, so I'm going to add another commonly used, more up to date, trick:
// 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使用。
The let touchEvent
should be declared out of function (also not in a document.ready) at the top of your javascript. This way you can use this in all your javascript. This also allows easy jQuery usage.
旧答案:
这解决了复制代码的需要(至少要少到最少)。不确定你是否可以将它们组合起来
This fixes the need for copying your code (well at least to a minimum). Not sure if you can combine them
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);
这篇关于在iphone上进行onclick工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!