Drop-down menu on touch based devices

2019-04-02 21:22发布

问题:

I have this navigation bar on my website and it doesn't drop down on my iPod touch, I suspect the same for iPhones and iPads. This is one of the pages

I was wondering if there is any quick fix to enable the touch/hover.

CSS

回答1:

If you are interested in iDevices, then you can use this trick:

#nav ul {
display: none;
/* Your styles */
}
#nav > li:hover ul {
display: block;
}
/* This is important */
#nav > li > a:hover {
color: #fff; /* You can set the same color or add other style.*/
}

If an element has the :hover event then the first tap iOS renders :hover and the second tap raises the click event.

That should work.

P.S. It's better to make different UI logic for mobile, touch and desktop.



回答2:

There's a good article on this here - http://www.nczonline.net/blog/2012/07/05/ios-has-a-hover-problem/

I'd suggest using Modernizr as it provides a no-touch CSS class you could use for touch screen devices, or you can use Javascript to detect hovers and add a class to your element.

if (!("ontouchstart" in document.documentElement)) {
    document.documentElement.className += " no-touch";
}


回答3:

The most elegant solution I've come across is by Osvaldas Valutis

His method involves a really tiny jQuery plugin to detect touch events on navigation list items with dropdown ul menus.

For example, you might mark up your navigation like this:

<nav id="nav-primary">
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about/">About</a>
            <ul>
                <li><a href="/about/index.html">Dropdown item 1</a></li>
                <li><a href="/about/page.html">Dropdown item 2</a></li>
            </ul>
        </li>
    </ul>
</nav>

You then call the plugin with a single line of jQuery like so:

$( '#nav-primary li:has(ul)' ).doubleTapToGo();

This ensures that the Home link in the example above still works as expected, since it doesn't have a dropdown menu. The only (very minor) drawback is that there's a little bit of redundancy in the first link on the dropdown, but that doesn't hurt.