我在我的移动视图上触发了一个ontouchstart事件,它链接到以下内容:
function mobileLinksShow() {
document.querySelector('.mobile-head-bar-links').classList.toggle('mobile-head-bar-links-transition');
}在我的设备(iPhone 5)上,当我点击按钮时,它会切换两次,因此它会伸展,然后收缩。这是因为onclick和ontouchstart同时触发。移除onclick解决了移动端的问题,但现在桌面浏览器显然不能工作了,有没有办法在移动端抑制onclick?
HTML:
<span class='mobile-head-bar-left' ontouchstart='mobileLinksShow()' onclick='mobileLinksShow()' ><i class="fa fa-bars"></i></span>CSS:
.mobile-head-bar-links {
height: 0;
overflow: hidden;
background-color: #F76845;
transition: .5s ease;
-webkit-transition: .5s ease;
}
.mobile-head-bar-links-transition {
height: 7em;
}注意:我不想使用jQuery。
发布于 2014-02-03 01:52:29
通过测试浏览器类型并相应地删除onclick,找到了一个解决方法:
function removeMobileOnclick() {
if(isMobile()) {
document.querySelector('.mobile-head-bar-left').onclick = '';
}
}
function isMobile() {
if (navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
|| navigator.userAgent.match(/Opera Mini/i)
|| navigator.userAgent.match(/IEMobile/i)
) {
return true;
}
}
window.addEventListener('load', removeMobileOnclick);这样就可以使onclick和ontouchstart都不受干扰
从和 webOS 部件中获取的函数已被删除,因为它将桌面浏览器视为移动设备。
发布于 2014-12-15 23:42:09
我只是想记住ontouchstart是否被触发过。在这种情况下,我们在一个支持它的设备上,并且想要忽略onclick事件。由于ontouchstart应该总是在onclick之前触发,所以我使用下面的代码:
<script> touchAvailable = false; </script>
<button ontouchstart="touchAvailable=true; myFunction();" onclick="if(!touchAvailable) myFunction();">Button</button>
发布于 2016-11-25 12:59:34
您可以将一个函数绑定到ontouchstart,该函数调用绑定到onclick的任何内容,但随后会阻止default,因此它实际上不会触发onclick。
然后,您可以轻松地将此ontouchstart事件复制粘贴到使用onclick的所有位置。
<span class='mobile-head-bar-left' ontouchstart='touch_start(event)' onclick='mobileLinksShow()' ><i class="fa fa-bars"></i></span>
<script>
function touch_start(e){
e.preventDefault();
e.target.onclick();
}
</script>https://stackoverflow.com/questions/21513596
复制相似问题