javascript - 父子悬停未按预期工作

标签 javascript jquery html css

我有一个这样的 HTML,其中内部是子 div,外部是父 div。

我必须实现的目标:激活鼠标悬停在上面的那个 div。

我调用了 jQuery 的悬停函数,它帮助我添加和删除事件类。

问题:当我将光标向上移动到 innerchild div 时,它被激活,但是当我将光标从内部 div 移出到外部父 div 时,它缓慢地被激活,外部没有被激活。

我也跟踪了鼠标的移动。 <强> https://jsfiddle.net/Simplybj/zaz1qh8e/2/ .

结果:当内部div悬停时,外部div的mouseout没有触发

 $('div').hover(
   function() {
     $('div').removeClass('activeHover');
     $(this).addClass('activeHover');
   },
   function() {
     $(this).removeClass('activeHover');
   }
 );
.outer {
  background-color: #aeaeae;
  height: 200px;
  width: 200px;
  float: left;
}
.inner {
  margin: 50px;
  background-color: #ccc;
  height: 100px;
  width: 100px;
  float: left;
}
.activeHover {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="outer">
  <div class="inner">

  </div>
</div>

最佳答案

如果你想实现这一点,你还需要监听 mousemove 事件。 此外,我添加了 event.stopPropagation(); 因此当您在 .inner div 中悬停或移动时,.outer 的事件将没有被解雇。

$('div').bind({
  mouseenter: eve,
  mousemove: eve,
  mouseout: function() {
    $(this).removeClass('activeHover');
  }
});

function eve(event) {
  event.stopPropagation();
  $('div').removeClass('activeHover');
  $(this).addClass('activeHover');
}
.outer {
  background-color: #aeaeae;
  height: 200px;
  width: 200px;
  float: left;
}
.inner {
  margin: 50px;
  background-color: #ccc;
  height: 100px;
  width: 100px;
  float: left;
}
.activeHover {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="outer">
  <div class="inner">

  </div>
</div>

关于javascript - 父子悬停未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408472/

相关文章:

javascript - 我的购物车不会重置(javascript 函数)

javascript - 过滤 Html 表的最有效方法?

php - 在 php 中保存 Canvas 但在图像文件中没有数据

html - 为什么打开一个宽度为480px的网站会有空白?

php - 通过 PHP 使用数组值生成自定义 HTML 表单

javascript - 使用高整数数组索引有什么负面影响吗?

javascript - Highcharts - 沿特定日期范围更改背景颜色

javascript - 如何通过 $routeParams 将 $scope 变量设置为 true?

jquery - 选项卡上的按键不起作用

html - 如何将 3 列全尺寸排成一行?