14

JavaScript で「onclick」を使用してきましたが、iPhone でも動作するようにしたいと考えています。ontouchstart をサポートするデバイスで、すべての「onclick」を ontouchstart のように動作させる簡単な方法はありますか?

それとも、すべてのスクリプトを 2 回 (1 つは onclick を使用し、もう 1 つは 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>
4

2 に答える 2

24

この投稿はより注目を集めたので、一般的に使用される別の最新のトリックを追加します。

// 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);
于 2013-09-20T10:34:39.707 に答える