CSS Dynamic Navigation with Hover - How Do I make

2019-03-13 16:34发布

问题:

In my site I use a CSS only dynamic menu. This is fine in desktop browsers, but not on iOS (iphone, ipad, etc) because the touch interface does not support the :hover selector.

My question is: what is the best way of supporting this on iOS? (Ideally either by patching with some CSS, or Javascript that will make the existing code work, rather than doing the whole thing over just to support iOS)

My html looks like this

<ul id="nav"> 
  <li> 
     Item 1
     <ul> 
       <li><a href=''>sub nav 1.1</a></li>
       <li><a href=''>sub nav 1.2</a></li>
     </ul> 
  </li> 
  <li> 
     Item 2
     <ul> 
       <li><a href=''>sub nav 2.1</a></li>
       <li><a href=''>sub nav 2.2</a></li>
     </ul> 
  </li> 
  <li> 
     Item 3 
     <ul> 
        <li><a href=''>sub nav 3.1</a></li>
        <li><a href=''>sub nav 3.2</a></li>
    </ul> 
  </li> 
</ul> ​​​​​

And the CSS is this

#nav li {
    float:left;
    padding:0 15px;
}

#nav li ul {
    position: absolute;
    width: 10em;
    left: -999em;
    margin-left: -10px;
}

#nav li:hover ul {
    left: auto;
}

I have done a jsfiddle of this here: http://jsfiddle.net/NuTz4/

回答1:

Check this article, perhaps it's a solution for you ;)

http://www.usabilitypost.com/2010/05/12/css-hover-controls-on-iphone/

Also JS solution, taken from: http://www.evotech.net/blog/2008/12/hover-pseudoclass-for-the-iphone/

var nav = document.getElementById('nav');
var els= nav.getElementsByTagName('li');
for(var i = 0; i < els.length; i++){
    els[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
    els[i].addEventListener('touchend', function(){this.className = "";}, false);
}

In jQuery:

$('#nav li').bind('touchstart', function(){
    $(this).addClass('hover');
}).bind('touchend', function(){
    $(this).removeClass('hover');
});

css:

li:hover, li.hover { /* whatever your hover effect is */ }