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

浏览:47日期:2024-01-13
如何解决$(document).click()在iPhone上无法正常工作。jQuery?

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

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

$(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_502_1@

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

更长的答案:@H_502_1@

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

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

<div class=’clickable-div’ data-href='http://www.stackoverflow.com'> ... clickable content here (images/text) ...</div>

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

$(document).on(’click’, ’.clickable-div’, function() { document.location = $(this).data(’href’);});

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

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

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

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

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

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

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

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

有任何想法吗?

相关文章: