首页 > 解决方案 > 如何在进行另一个函数调用时停止执行 javascript/jquery

问题描述

我对 JavaScript 的理解不是很好,但我一直在尝试用它在我孩子的网站experimonkey.com上制作一些交互功能。我的最新想法之一是当用户将鼠标悬停在相应的菜单项上时,使用 JQuery 的toggle()函数在主页弹出菜单上显示带有附加信息的菜单项。这几乎完成了我想要做的事情,除非你开始过快地将鼠标悬停在链接上,事情变得非常奇怪......每个函数调用都会执行完成并且浏览器开始滞后。

有没有办法解决这个问题,以便一次只有一个元素在队列中?我一开始就完全错了吗?下面是我正在使用的代码示例。

function show(id) {
  $(document).ready(function() {
    $("#" + id).slideToggle();
  });
}
.hidden {
  display: none;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<div class="col-6  col-sm-4 col-lg-2 tile p-1">
  <a href="/edu-center" onmouseenter="show('edu-center')" onmouseout="show('edu-center')">
    <div class="card">
      <div class="card-header" id="tile-edu-center"></div>
      <div class="card-body text-center">
        <h5>Edu-center</h5>
        <small id="edu-center" class="hidden">Science research and information for kids</small>
      </div>
    </div>
  </a>
</div>

标签: javascriptjqueryhtmlcss

解决方案


另一种方法是使用:hover伪类。现在,对于动画,您可以使用max-height.

.hidden {
  display: inline-block;
  max-height: 0px;
  overflow: hidden;
}

small {
  transition: all 0.5s ease-in-out;
}

a:hover small {
  max-height: 1000px;
  height: auto;
  transition: all 1s ease-in-out;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<div class="col-6  col-sm-4 col-lg-2 tile p-1">
  <a href="/edu-center">
    <div class="card">
      <div class="card-header" id="tile-edu-center"></div>
      <div class="card-body text-center">
        <h5>Edu-center</h5>
        <small id="edu-center" class="hidden">Science research and information for kids</small>
      </div>
    </div>
  </a>
</div>


推荐阅读