2017-08-10 48 views
0

我在jQuery中使用fadeIn和fadeOut,它在桌面上工作正常。但是,在移动设备上(我只在iPhone上测试过),触摸外部元素后,子div会触摸但不会隐藏。我对jQuery相当陌生,所以我不确定我可以在这里实现什么样的解决方案。也许移动检测和执行触摸来打开/隐藏,但我不知道如何做到这一点。这里是我的jsfiddle:jQuery:淡入淡出/淡入淡出 - 移动设备上的替代品?

https://jsfiddle.net/9LL3mmzt/

的jQuery:

$(document).ready(function() { 
    $(".parent").hover(function() { 
    $(this).children(".child").fadeIn("fast"); 
    }, function() { 
    $(this).children(".child").fadeOut("fast"); 
    }); 
}); 

HTML:

<div class="parent"> 
    <span>Peek-A-</span> 
    <div class="child"> 
    <span>Boo</span> 
    </div> 
</div> 

CSS:

.child { 
    display: none; 
} 

我试图从该线程中的第一个解决方案: time-out on jQuery hover function

但是,由于我的知识有限,无法正常工作。

回答

1

悬停功能并非真的应该在触控设备上使用。我认为你需要检查touchstart功能。

编辑1: 一个例子是这样的:

$('div.example').on("touchstart", function (e) { 
    alert('testing'); 
}); 

但是要记住,你仍然可以使用你的悬停JavaScript,但你必须只使用它没有触摸设备指定。请参阅Modernizr

希望这会有所帮助。

仅供参考@James Douglas您可以看到我无法发表任何评论,因为我的声誉得分。如果可能请评论或帮助我们找到这个问题的答案,我认为这会更有用。

编辑2:Modernizr非常方便。在你的情况下,你会得到一个类的触摸或不触摸(在html元素),取决于你是哪个设备。

所以在我的例子中,你可以使用它那么作为$(“触摸div.example”)......

有可能不同的解决方案,但我认为这是最好的办法(另见What's the best way to detect a 'touch screen' device using JavaScript?)。您只需将de modernizr.js文件添加到您的网站(最好在您的网页的头部)。

编辑3:我测试了你的jsfiddle在iPhone和Android上的例子,它的工作原理。所以对我来说这是一件好事。

+0

如果你愿意详细一点日请编辑你的答案。如果没有,您应该将其作为评论发布。 –

+0

@Nick一个例子会很好! –

+0

@Nick,是否可以使用if/else语句而不是使用Modernizr?看起来它太复杂了。 –

0

我是能够使这项工作(至少在iPhone上),使用从@尼克的帖子的例子,从线程我在OP连接解决方​​案:

这里的的jsfiddle:https://jsfiddle.net/tkeaoffd/

JQuery的:

$(document).ready(function() { 
    function hasTouch() { 
    try { 
     document.createEvent("TouchEvent"); 
     return (true); 
    } catch (e) { 
     return (false); 
    } 
    } 
    var touchPresent = hasTouch(); 
    $('.parent').hover(function() { 
    var caption = $(this).find('.child'); 
    caption.stop(true, true).fadeIn("fast"); 
    if (touchPresent) { 
     $('.parent').on("touchstart", function(e) { 
     $(this).children(".child").fadeToggle("fast"); 
     }); 
    } 
    }, function() { 
    $(this).find('.child').stop(true, true).fadeOut("fast"); 
    }); 
}); 

HTML/CSS:

<div class="parent"> 
    <span>Peek-A-</span> 
    <div class="child"> 
    <span>Boo</span> 
    </div> 
</div> 


.child { 
    display: none; 
}