简体   繁体   中英

css :hover, touch-screen and single page applications

I'm making a single-page application with HTML, CSS and Javascript (no jQuery or similar). This application is made of many UI pages that can change via Javascript. The user experience is fine using the mouse on computers, but not so nice with touchscreens (mobile, etc.).

There are many buttons with a CSS hover graphic effect. If I change page tapping one button on a touch screen, the pointer stays there triggering the CSS hover of next elements appearing in the same position when the page is "changed". This effect is very annoying, but I can't figure out how to fix it.

The code is very simple:

CSS

button {
    background-color: #XXXXXX;
}

button:hover {
    background-color: #ZZZZZZ;
}

HTML

<button onclick="changepage()"></button>

You can use modernizr with Touch Events detection, than use

html.no-touch button:hover {
    background-color: #ZZZZZZ;
}

Without modernizr you can add this simple code to append no-touch/touch class to html tag

 <script type="text/javascript">

    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Phone/i.test(navigator.userAgent)) {
       document.getElementsByTagName('html')[0].className += ' touch';
    }else{
       document.getElementsByTagName('html')[0].className += ' no-touch';
    }

 </script>

Thank you anyway! Finally I made a very simple script that works perfectly...it is good even for touch computers that have a mouse too (like mine), and of course for mobile phones. There is no need to detect devices! The solution is to add a very small div under the cursor pointer after the page changes, by calling the function refresh_hover(). This div 1px x 1px is removed as soon as the user clicks on it or the cursor goes out from it. In this way the hover effect is removed when the content changes behind the pointer, but then restored when the user does something! You will probably think that is very stupid, but is simple and works very well!

Here it is:

function refresh_hover(){

    if(!event){
        return false;
    }

    var x = event.clientX;
    var y = event.clientY;

    var div = document.getElementById('mouse_div');

    if(!div){
        document.body.innerHTML=document.body.innerHTML
        +'<div style="position: fixed; z-index: 1000; height: 1px; width: 1px; display: block;" id="mouse_div" onmouseout="this.style.display=\'none\'" onclick="this.style.display=\'none\'"></div>';
        div = document.getElementById('mouse_div');
    }


    div.style.display='block';
    div.style.top=y+'px';
    div.style.left=x+'px'
}

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