我在尝试解决这个问题时遇到了一些麻烦。我无法让 JQuery .click() 事件在 iOS Safari 上运行,即使在针对此问题尝试了一些已知的解决方法之后也是如此。
我的代码:
HTML:
<div class="mobile-nav-menu">
<a href="#" onclick="void(0)">
<img id="hamburger-menu-icon" src="assets/dot-menu.svg">
</a>
</div>
JS(省略变量声明以节省长度):
window.onload = () => {
hamburgerMenuIcon.click(toggleMobileNavDropdown);
}
const toggleMobileNavDropdown = () => {
if(mobileNavDropdown.height() == 0) {
mobileNavDropdown.css({
height: '180px',
width: '200px'
})
mobileNavContents.delay(800).fadeIn(900);
} else if(mobileNavDropdown.height() == 180) {
mobileNavContents.fadeOut(400);
setTimeout(() => {
mobileNavDropdown.css({
height: '0px',
width: '0px'
})
}, 400)
}
}
这在除 Safari iOS 之外的任何浏览器(包括移动设备或桌面设备)中绝对没有问题。我在谷歌上花了一些时间,发现了一些已知的解决方法。这是我迄今为止尝试过但没有成功的方法:
我已尝试将
cursor: pointer;
应用于链接。据我所知,如果没有这个 Safari,iOS 不会将该元素注册为可点击。由于添加光标 CSS 属性不起作用,我尝试将
onclick="void(0)"
添加到 HTML,如上面的 HTML 片段所示。这是我在 Stack 上遇到的另一个建议,我假设它以某种方式允许 Safari iOS 将元素注册为可点击。在我的第三次尝试中,我尝试将点击事件更改为 vanilla JS 并添加
touchstart and tap
:hamburgerMenuIcon.on("click touchstart tap", toggleMobileNavDropdown);
到目前为止,什么都没有。有什么建议么?
最佳答案
我这样做,首先这部分是为了阻止由于我接下来要做的冒泡而多次发生的事件:
function eventHandler(event, selector) {
event.stopPropagation(); // Stop event bubbling.
event.preventDefault(); // Prevent default behaviour
if (event.type === 'touchend' || event.type === 'touchcancel')
selector.off('click'); // If event type was touch turn off clicks to prevent phantom clicks.
}
然后对于实际的元素交互(你不一定需要去抖动部分,但我发现它很有帮助,如果你喜欢我会链接你那个插件,它非常轻巧且有用):
$(".selection-button").on('click touchend touchcancel', $.debounce(
100,
function(e) {
//whatever you want to do
}));
关于javascript - jQuery .click() 即使在尝试了一些已知修复后也无法在 iOS Safari 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525196/