我必须在移动设备中三次点击我的网站正文时显示和隐藏 div 我用 JavaScript 编写的以下代码在 Android 设备中运行良好,但在 IOS 中不起作用。 那么你能帮我解决这个问题吗?
代码是:
window.onload = function() {
document.querySelector('body').addEventListener('click', function(evt) {
evt.preventDefault();
if (evt.detail === 3) {
document.getElementById('mmu').style.height = '100px';
}
if (evt.detail === 1) {
document.getElementById('mmu').style.height = '0px';
}
});
}
#mmu {
width: 100px;
height: 0px;
position: fixed;
left: 0;
cursor: pointer;
top: 0;
background: red;
}
body {
height: 1000px;
background: #eee;
width: 100%;
cursor: pointer;
}
<div id="mmu"></div>
最佳答案
在 iOS 上,click
事件无法正常触发。相反,您需要监视触摸事件,例如 touchend
检查点击了多少次。
例如,您可能会尝试检查点击是否是在足够的超时窗口内进行的,如下所示
TOUCH_TIMEOUT_MILLISECONDS = 500
touch_count = 0
window.onload = function () {
document.querySelector('body').addEventListener('touchend', function (evt) {
touch_count += 1
setTimeout(function () {
touch_count = 0
}, TOUCH_TIMEOUT_MILLISECONDS);
if (touch_count === 3) {
document.getElementById('mmu').style.height = '100px';
}
if (touch_count === 1) {
document.getElementById('mmu').style.height = '0px';
}
evt.preventDefault();
});
});
根据您的要求,您可能还需要考虑同一操作触发的 touchend
和 click
事件。
关于javascript - 如何检测ios设备上网站的三次点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773096/