onclick和ontouchstart同时进行

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.

use*_*607 7

通过测试浏览器类型并相应地删除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删除的部分,因为这将桌面浏览器视为移动设备.

  • 由于触摸设备而导致的糟糕方法不仅限于手机(在 2014 年也不例外)。 (3认同)

jak*_*b.j 6

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)


maj*_*aja 0

你可以这样写:

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)

但是:如果使用此代码,即使单击跨度两次,该函数也只能调用一次。