使用touchstart和touchend模拟hover或者mouseup和mousedown事件

3

我需要在iPhone菜单中模拟悬停或鼠标按下/松开的效果,以下是两个示例。

<ul id="main_nav">
    <li><a href="http://google.com">google</a></li>
    <li><a href="http://yahoo.com">yahoo</a></li>
    <li><a href="#">Three</a>
      <ul>
        <li><a href="#">sub One</a></li>
        <li><a href="#">sub Two</a></li>
      </ul>
</li>
<li><a href="#">Four</a></li>
</ul>

//bind the touchstart event to the link element
$('li').live('touchstart touchend', function(e){
    $(this).toggleClass('btn-sign-up-hover');
    //alert('alert');
});

a {
    display:block;
    line-height:30px;

}

li{
    background:#096;
}

.btn-sign-up-hover {
    background: #F3F;
}

这在iPhone上不起作用,

但以下内容可以正常工作

//bind the touchstart event to the link element
$('li').live('touchstart', function(e){
    $(this).css('background','red');
    //alert('alert');
});

$('li').live('touchend', function(e){
    $('li').css('background','#096');
    //alert('alert');
});

问题是我需要使用toggleClass。
示例代码请参考http://jsfiddle.net/UcyAb/
2个回答

7
//bind the touchstart event to the link element
$('li').live('touchstart', function(e){
    $(this).addClass('btn-sign-up-hover');
    //alert('alert');
});

$('li').live('touchend', function(e){
    $('li').removeClass('btn-sign-up-hover');
    //alert('alert');
});

希望这能顺利完成。


1
希望能够使用纯CSS或者最坏情况下使用纯JS的解决方案,不需要使用JQuery。 - undefined
你可以使用toggleClass和add两个事件来实现只有一个函数。 - undefined

0
我一直在使用类似于@Sameera Thilakasiri的答案的解决方案,但是我在iPad上遇到了一个问题,即点击菜单项时会触发两个点击事件 - 一个是被点击的菜单项,另一个是菜单下方(按照z-index顺序)的其他内容。对我有效的解决方案是在touchend事件中触发轻微延迟。希望这对某人有所帮助!
$('.touchHover').bind('touchstart',function(){
     $(this).addClass('hovered');
     }).bind('touchend',function(){
     $t=setTimeout(function(){$(this).removeClass('hovered');},10);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接