简体   繁体   中英

CSS :focus automatically opens link on android device

On a website I use :hover for web and :focus for touch device on a link. But on android devices if I touch the link it do the :focus but then automatically open the link.

It should do the :focus and if the user clicks again on the link, then it should open the link. Is this possible with pure CSS?

I got a short example of my :hover and :focus code:

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

There is no problem on iOS (works perfectly on iOS). Just on android devices.

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. There are other methods to check for touch but Modernizr will get you the best results in my opinion.

So first include Modernizr. You can download it from their website or use a cdn like cdnjs.com

<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:

$(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() . 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. I couldn't test it all the way through but it should work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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