父子徘徊不按预期工作

时间:2016-02-15 11:42:31

标签: javascript jquery html css

我有一个像这样的HTML,其中inner是子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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

如果您想实现这一目标,您还需要收听mousemove事件。 另外,我添加了event.stopPropagation();,因此当您悬停或移入.inner div时,.outer的事件不会被触发。

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

function eve(event) {
  event.stopPropagation();
  $('div').removeClass('activeHover');
  $(this).addClass('activeHover');
}
&#13;
.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;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="outer">
  <div class="inner">

  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我尝试使用jquery为mouseover和mouseleave分别使用函数,并且正在为我工​​作。你能试试吗?

this.setState({
  topicPageNo: 0,
  total_selected_topic_pages: 1,
  topicsVisited: []
});
$(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;
}

相关问题