简体   繁体   English

CSS:focus自动在Android设备上打开链接

[英]CSS :focus automatically opens link on android device

On a website I use :hover for web and :focus for touch device on a link. 在网站上,我将:hover用于网络,将:focus用于触摸设备上的链接。 But on android devices if I touch the link it do the :focus but then automatically open the link. 但是在android设备上,如果我触摸链接,它将执行:focus ,然后自动打开链接。

It should do the :focus and if the user clicks again on the link, then it should open the link. 它应该执行:focus ,如果用户再次单击该链接,则应该打开该链接。 Is this possible with pure CSS? 纯CSS可以做到吗?

I got a short example of my :hover and :focus code: 我得到了:hover:focus代码的简短示例:

#menu li:hover ul.sub-menu, #menu li:focus ul.sub-menu{
    display:block;
}

There is no problem on iOS (works perfectly on iOS). 在iOS上没有问题(在iOS上完美运行)。 Just on android devices. 只是在android设备上。

You will need a bit of javascript (jQuery, which is already included in your site) and Modernizr to determine if the user is on a touchscreen device. 您将需要一些javascript(jQuery,它已经包含在您的网站中)和Modernizr来确定用户是否在触摸屏设备上。 There are other methods to check for touch but Modernizr will get you the best results in my opinion. 还有其他检查触摸的方法,但我认为Modernizr将为您带来最佳效果。

So first include Modernizr. 因此,首先包括Modernizr。 You can download it from their website or use a cdn like cdnjs.com 您可以从他们的网站下载它,也可以使用cdnjs.com这样的CDN

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js"></script>

After that, add this javascript to your site: 之后,将此JavaScript添加到您的网站:

$(document).ready(function(){
    if(Modernizr.touch){
        $('#menu-mainmenu').on('click', '> li', function(e){
            if(!$(this).data('open')){
                e.preventDefault();
            }
            $(this).data('open', true);
        });
    }
});

So if you're on a touch device and click on a mainmenu-item then submenu pops up (due the :focus styling) but the link is blocked because of e.preventDefault() . 因此,如果您在触摸设备上并单击主菜单项,则会弹出子菜单(由于:focus样式),但由于e.preventDefault() ,链接被阻止。 Then the data-value "open" is set to true, so if the user taps on the link again, the if check fails and the link opens normally. 然后将数据值“ open”设置为true,因此,如果用户再次点击该链接,则if检查失败,并且该链接正常打开。 I couldn't test it all the way through but it should work... 我无法一直进行测试,但是应该可以...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM