父子悬停未按预期工作

Parent child Hover not working as expected

本文关键字:工作 悬停 父子      更新时间:2023-09-26

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

我必须实现的:激活鼠标悬停的div。

我已经调用了jQuery的悬停函数,它正在帮助我附加和删除活动类。

问题:当我将光标向上移动到内部子div 时,它被激活,

但当我将光标从内部div 移动到外部父div 时,外部没有被激活。

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

结果:当内部div 悬停时,不会触发外部div 的鼠标退出

 $('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();因此当您悬停或移动到.innerdiv 中时,.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>

我用jquery尝试了鼠标悬停和mouseleave的单独函数,并且正在为我工作。你能试试这个吗?

$(document).ready(function(){
  $('.inner').mouseenter(function(){
    $(this).addClass('activeHover');
    $('.outer').removeClass('activeHover');
  });
  $('.outer').mouseenter(function(){
    $(this).addClass('activeHover');
    $('.inner').removeClass('activeHover');
  });
  $('.inner').mouseleave(function(){
    $(this).removeClass('activeHover');
    $('.outer').addClass('activeHover');
  });
  $('.outer').mouseleave(function(){
    $('.outer').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://code.jquery.com/jquery-1.10.2.js"></script>
<div class="outer">
  <div class="inner">
  </div>
</div>
<ul class="mousemovement">
</ul>