1. ホーム
  2. javascript

[解決済み] iPhoneで$(document).click()が正しく動作しない。

2022-10-31 06:46:28

質問

この機能はIE、Firefox、Chromeでは完璧に動作しますが、iPhoneでは <img> . ページ上(img以外)をクリックしてもイベントは発生しません。

$(document).ready(function () {
  $(document).click(function (e) {
    fire(e);
  });
});

function fire(e) { alert('hi'); }

HTML部分は極めて基本的なものであり、問題ないはずです。

何かアイデアはありますか?

どのように解決するのですか?

以下のコードを追加すると動作します。

問題は、iPhoneはクリックイベントを発生させないということです。彼らは "touch" イベントを発生させます。ありがとうございます、Apple。なぜ他の人たちのように標準のままにしておくことができなかったのでしょうか? とにかく、ヒントをくれた Nico に感謝します。

クレジットに http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript

$(document).ready(function () {
  init();
  $(document).click(function (e) {
    fire(e);
  });
});

function fire(e) { alert('hi'); }

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";

    switch(event.type)
    {
       case "touchstart": type = "mousedown"; break;
       case "touchmove":  type = "mousemove"; break;        
       case "touchend":   type = "mouseup"; break;
       default: return;
    }

    //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //           screenX, screenY, clientX, clientY, ctrlKey, 
    //           altKey, shiftKey, metaKey, button, relatedTarget);

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0/*left*/, null);

    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() 
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}