微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

$document.click在iPhone上无法正常工作jQuery

如何解决$document.click在iPhone上无法正常工作jQuery

@H_404_0@添加以下代码即可。

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

$(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);    
}
@H_404_0@简短答案:

<style>
    .clickable-div 
    {
         cursor: pointer;
    }
</style>
@H_404_0@更长的答案:

@H_404_0@重要的是要意识到,如果你只是使用标签,那么一切都会按预期工作。你可以在iPhone 上的常规链接上错误地单击或拖动,并且所有行为均与用户期望的一样。

@H_404_0@我想象你有一些不可单击的HTML,例如包含不能用包裹的文本和图像的面板。当我有一个我想完全可以单击的面板时,我发现了这个问题。

<div class='clickable-div' data-href="http://www.stackoverflow.com">

 ... clickable content here (images/text) ...

</div>
@H_404_0@为了检测该div中任何位置的点击,我正在使用具有data-hrefhtml属性的jQuery,如上所示(此属性是我自己发明的,不是标准的jQuery或HTML数据属性。)

$(document).on('click', '.clickable-div', function() {

    document.location = $(this).data('href');

});
@H_404_0@无论点击多少,这都将在你的桌面浏览器上运行,但不适用于iPad。

@H_404_0@你可能会想将事件处理程序从更改click为click touchstart-确实确实触发了事件处理程序。但是,如果用户想要向上拖动页面(滚动),他们也会触发该页面-这是糟糕的用户体验。[你可能已经通过偷偷摸摸的横幅广告注意到了这种行为]

@H_404_0@答案非常简单:只需设置CSS即可cursor: pointer。

<style>
    .clickable-div 
    {
         cursor: pointer;
    }
</style>
@H_404_0@这为桌面用户带来了额外的好处,即桌面图标可以用一个手形图标单击。

解决方法

此功能在IE,Firefox和Chrome上均能完美运行,但在iPhone上,仅在单击时才能使用<img>。单击页面(除了img以外的任何地方)都不会触发该事件。

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

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

HTML部分非常基础,不应成为问题。

有任何想法吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。