onclick和ontouchstart [英] onclick and ontouchstart simultaneously

查看:227
本文介绍了onclick和ontouchstart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个移动视图触发的 ontouchstart 事件,其链接到:

I have an ontouchstart event triggered on my mobile view, its linked to this:

function mobileLinksShow() {
    document.querySelector('.mobile-head-bar-links').classList.toggle('mobile-head-bar-links-transition');
}



在我的设备(iPhone 5)上,当我点击按钮,两次,因此它延长然后合同。这是因为onclick和ontouchstart同时触发。移除onclick可解决移动设备上的问题,但现在桌面浏览器显然无法正常工作,是否有办法禁止移动设备上的onclick?

On my device (iPhone 5) when I tap the button, it toggles it twice and so it extends then contracts. This is because of the onclick and ontouchstart firing at the same time. Removing the onclick solves the issue on mobile but now the desktop browser clearly doesnt work, is there a way to suppress onclick on mobile?

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。

NB. I don't want to use jQuery.

推荐答案

通过测试浏览器类型并相应地删除onclick发现一个工作: / p>

Found a work around by testing the browser type and removing the onclick accordingly:

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 不干扰

This way you can have both onclick and ontouchstart not interfering

isMobile函数取自检测移动设备 webOS 部分已删除,因为这将桌面浏览器视为移动设备。 / em>

isMobile function taken from Detecting mobile devices and the webOS part removed as this saw the desktop browser as mobile.

这篇关于onclick和ontouchstart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆