$(document).click() 在 iPhone 上无法正常工作.查询 [英] $(document).click() not working correctly on iPhone. jquery

查看:29
本文介绍了$(document).click() 在 iPhone 上无法正常工作.查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此功能在 IE、Firefox 和 Chrome 上完美运行,但在 iPhone 上,它仅在单击 时才有效.单击页面(除了 img 之外的任何地方)都不会触发该事件.

This function works perfectly on IE, Firefox and Chrome but when on the iPhone, it will only work when clicking on a <img>. Clicking on the page (anywhere but on a img) wont fire the event.

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

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

HTML 部分非常基础,应该不会有问题.

The HTML part is extremely basic and shouldnt be a problem.

有什么想法吗?

推荐答案

添加以下代码即可.

问题是 iPhone 不会引发点击事件.它们引发触摸"事件.非常感谢苹果.为什么他们不能像其他人一样保持标准?无论如何,感谢 Nico 的提示.

The problem is iPhones dont raise click events. They raise "touch" events. Thanks very much apple. Why couldn't they just keep it standard like everyone else? Anyway thanks Nico for the tip.

归功于: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);    
}

这篇关于$(document).click() 在 iPhone 上无法正常工作.查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆