当前位置:Gxlcms > JavaScript > jQuery中下拉菜单mouseover和mouseout反复触发的解决方法

jQuery中下拉菜单mouseover和mouseout反复触发的解决方法

时间:2021-07-01 10:21:17 帮助过:20人阅读

网上找到的解决办法是改为mouseenter和mouseleave事件,改过之后还是不行。鼠标滑过触发区域,下拉菜单会反复弹出、隐藏。

1625.png

  1. //purProduction为“购买产品”的id,showPurchase为下拉菜单的id
  2. $("#purProduction").mouseenter(function() {
  3. $("#showPurchase").slideDown();
  4. })
  5. $("#purProduction").mouseleave(function() {
  6. $("#showPurchase").slideUp();
  7. })
  8. $("#showPurchase").mouseenter(function(){
  9. $("#showPurchase").slideDown();
  10. })
  11. $("#showPurchase").mouseleave(function(){
  12. $("#showPurchase").slideUp();
  13. })
  14. <a class="name" id="purProduction" style="padding:20px;position:relative;left:1px;top:10px;">购买产品</a>
  15. <div class="showDiv" id="showPurchase" style="position:absolute;left:595px;top:50px;">
  16. <!-- 向上的箭头 -->
  17. <div class="outTri"></div>
  18. <div class="inTri"></div>
  19. <a class="item" style="display:block;font-size:15px;border-bottom:1px solid rgb(240,243,244)">查询价格</a>
  20. <a class="item" style="display:block;font-size:15px;border-bottom:1px solid rgb(240,243,244)">等级购买</a>
  21. <a class="item" style="display:block;font-size:15px;border-bottom:1px solid rgb(240,243,244)">经销商查询</a>
  22. <a class="item" style="display:block;font-size:15px;border-bottom:1px solid rgb(240,243,244)">合作加盟</a>
  23. </div>

关于你说的『反复弹出』
其实是这样的:鼠标移到purProduction上,触发弹出purProduction的mouseenter;此时鼠标再移动到showPurchase上时,会触发什么事件呢?首先鼠标离开了purProduction,触发它的mouseleave,然后鼠标进入showPurchase,触发mouseenter……这还好,看起来也就收起一次再弹出一次而已,然而slideDown过程中也是会触发事件的,当showPurchase在slideDown过程中反复经过鼠标附近的时候,就会反复触发鼠标事件……

解决方法很简单。最好的办法是弃用这套机制改用hover。当然如果你很不舍得你的代码想留用,那就要考虑用Interval来定时检查了……比如这样(不要怪我写得丑,其实这事应该CSS定制)

  1. //purProduction为“购买产品”的id,showPurchase为下拉菜单的id$("#showPurchase").slideUp();var show=false, showed=false;setInterval(function () {
  2. if (show && !showed) {
  3. $("#showPurchase").slideDown();
  4. showed=true;
  5. } else if (!show && showed) {
  6. $("#showPurchase").slideUp();
  7. showed=false;
  8. }}, 100);$("#purProduction").mouseenter(function() {
  9. show=true;})$("#purProduction").mouseleave(function() {
  10. show=false;})$("#showPurchase").mouseenter(function() {
  11. show=true;})$("#showPurchase").mouseleave(function(){
  12. show=false;})

是因为你的事件队列里面全是mouseover和mouseout的,要么使用:hover控制样式,要么就像上面说的用stop方法去清空之前的事件队列。

怎么有种知乎变成 StackOverflow 的感觉……

这是因为鼠标事件多次触发之后,节点的动画队列里堆积了多次 slideDown 和 slideUp,改成 $('#showPurchase').stop(true).slideDown() 应该就好了。

两种方法
第一种最简单,把你的下拉菜单和按钮放到一个容器里面,只需要给该容器绑定你说的两个事件即可,其实你可以使用hover(),如果不是必须加效果还是用:hover比较简单。
第二种结构不变的情况下实现起来略麻烦,需要使用setTimeout,一般tooltip的就是这样子的实现。

以上就是jQuery中下拉菜单mouseover和mouseout反复触发的解决方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行