use*_*607 9 html javascript css touch
我的ontouchstart移动视图触发了一个事件,它与此链接:
function mobileLinksShow() {
document.querySelector('.mobile-head-bar-links').classList.toggle('mobile-head-bar-links-transition');
}
Run Code Online (Sandbox Code Playgroud)
在我的设备(iPhone 5)上,当我点击按钮时,它会将其切换两次,因此它会延伸然后收缩.这是因为onclick和ontouchstart同时触发.删除onclick解决了移动设备上的问题,但现在桌面浏览器显然无法正常工作,是否有办法抑制移动设备上的onclick?
HTML:
<span class='mobile-head-bar-left' ontouchstart='mobileLinksShow()' onclick='mobileLinksShow()' ><i class="fa fa-bars"></i></span>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
NB.我不想使用jQuery.
通过测试浏览器类型并相应地删除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);
Run Code Online (Sandbox Code Playgroud)
这样你既可以兼顾onclick,也可以ontouchstart不干扰
isMobile功能取自检测移动设备和webOS删除的部分,因为这将桌面浏览器视为移动设备.
ontouchstart我只是想到了记住是否被触发的想法。在这种情况下,我们使用的是支持它的设备并希望忽略该onclick事件。因为应该总是在之前ontouchstart触发,所以我使用这个: onclick
<script> touchAvailable = false; </script>
<button ontouchstart="touchAvailable=true; myFunction();" onclick="if(!touchAvailable) myFunction();">Button</button>Run Code Online (Sandbox Code Playgroud)
你可以这样写:
var called = false;
function mobileLinksShow() {
if(!called)
document.querySelector('.mobile-head-bar-links').classList.toggle('mobile-head-bar-links-transition');
called = true;
}
}
Run Code Online (Sandbox Code Playgroud)
但是:如果使用此代码,即使单击跨度两次,该函数也只能调用一次。
| 归档时间: |
|
| 查看次数: |
26341 次 |
| 最近记录: |