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

本文介绍了在iPhone上遇到的$(document).click()事件不触发的问题,以及解决方案。当在iPhone上使用jQuery时,由于iPhone触发的是触摸事件而非点击事件,导致事件监听器不起作用。文章提供了通过监听触摸事件并模拟鼠标事件来解决这个问题的方法,并给出了相关代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何解决$(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);
}
简短答案:

更长的答案:

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

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

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

$(document).on('click', '.clickable-div', function() {
document.location = $(this).data('href');
});
无论点击多少,这都将在你的桌面浏览器上运行,但不适用于iPad。

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

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

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

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

$(document).ready(function () {
$(document).click(function (e) {
fire(e);
});
});
function fire(e) { alert('hi'); }
HTML部分非常基础,不应成为问题。

有任何想法吗?
声明:地推任务网所有作品(图片、文字)均由用户自行上传分享,仅供网友学习交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dituirenwu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值