添加/删除类,当您将鼠标悬停在父级上时,所有子元素的时间间隔

时间:2016-08-26 07:56:20

标签: javascript jquery

有一些带有子元素的元素,当你悬停时,应该在间隔后将子元素添加到类中。

我可以添加该类能够悬停,当我从父类中删除鼠标时首先删除,然后由于某种原因再次添加,我不明白发生了什么。

$('.field_icon')
  .mouseover(function() {
    $(this).children('.field-item').each(function(i, el) {
      setTimeout(function() {
        $(el).addClass('active');
      }, 100 + (i * 300));
    })
  })
  .mouseleave(function() {
    $(this).children('.field-item').removeClass('active')
  })
.field-item {
  display: inline-block;
  width: 50px;
  height: 50px;
  background: #7CB342;
}
.field-item.active {
  background: #FF9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>

2 个答案:

答案 0 :(得分:3)

您需要使用mouseleave事件中的clearTimeout清除超时间隔;

&#13;
&#13;
//Declare an empty array to store the timeoutID 
var t = [];
$('.field_icon')
  .mouseover(function() {
    $(this).children('.field-item').each(function(i, el) {

      //store the reference in a variable
      var t1 = setTimeout(function() {
        $(el).addClass('active');
      }, 100 + (i * 300));

      //Push it the array
      t.push(t1);
    })
  })
  .mouseleave(function() {
    //iterate and Clears the delay set setTimeout
    t.forEach(clearTimeout);

    //reset array to  emepty
    t.length = 0;
    $(this).children('.field-item').removeClass('active')
  })
&#13;
.field-item {
  display: inline-block;
  width: 50px;
  height: 50px;
  background: #7CB342;
}
.field-item.active {
  background: #FF9800;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
<div class="field_icon">
  <div class="field-item"></div>
  <div class="field-item"></div>
  <div class="field-item"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用mouseenter,而不是鼠标悬停:

http://www.w3schools.com/jquery/event_mouseover.asp

  

与mouseenter事件不同,如果鼠标指针进入任何子元素以及所选元素,则会触发mouseover事件。只有当鼠标指针进入所选元素时才会触发mouseenter事件。

因此,基本上,当您将鼠标移到子元素上时,它会在父元素获取子元素移动时再次重新添加所有事件。