您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

添加以下代码即可。

问题是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);    
}

简短答案:

<style>
    .clickable-div 
    {
         cursor: pointer;
    }
</style>

更长的答案:

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

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

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

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

</div>

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

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

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

});

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

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

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

<style>
    .clickable-div 
    {
         cursor: pointer;
    }
</style>

这为桌面用户带来了额外的好处,即桌面图标可以用一个手形图标单击。

JS 2022/1/1 18:17:16 有494人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶