CSS Dynamic Navigation with Hover - How Do I make it work in iOS Safari?

半世苍凉 提交于 2020-01-30 23:14:58

问题


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 */ }


来源:https://stackoverflow.com/questions/3501586/css-dynamic-navigation-with-hover-how-do-i-make-it-work-in-ios-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!