在孩子上面时触发mouseleave

时间:2015-06-30 16:00:40

标签: javascript jquery html hover

我被困在可能很容易解决的问题上,但我无法做到。我希望我的父母的风格在我悬停时改变,但当我将父母的孩子盘旋时恢复正常。

HTML:

<div id="parent">
   <div id="child"></div>
</div>

JS / jQuery的:

$('#parent').on({
    mouseenter: function (event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $(this).css("box-shadow", "inset 0 0 0 1000px green");
    },
    mouseleave: function (event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $(this).css("box-shadow", "inset 0 0 0 0px pink");
    }
});

小提琴:

Fiddle

2 个答案:

答案 0 :(得分:1)

使用鼠标悬停和鼠标移除并检测鼠标悬停时触发的元素。

$('#parent').on({
  mouseover: function(event) {
    if (!$(this).is(event.target)) return;
    event.stopPropagation();
    event.stopImmediatePropagation();
    $(this).css("box-shadow", "inset 0 0 0 1000px green");
  },
  mouseout: function(event) {
    event.stopPropagation();
    event.stopImmediatePropagation();
    $(this).css("box-shadow", "inset 0 0 0 0px pink");
  }
});
#parent {
  background-color: pink;
  width: 200px;
  height: 200px;
}
#child {
  position: relative;
  left: 75px;
  top: 75px;
  background-color: blue;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
  <div id="child"></div>
</div>

答案 1 :(得分:0)

RiggsFolly评论工作将JS改为:

$('#parent').on({
    mouseenter: function (event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $(this).css("box-shadow", "inset 0 0 0 1000px green");
    },
    mouseout: function (event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $(this).css("box-shadow", "inset 0 0 0 0px pink");
    }        
});
$('#child').on({
    mouseenter: function (event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $("#parent").css("box-shadow", "inset 0 0 0 0px green");
    },
    mouseleave: function (event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $("#parent").css("box-shadow", "inset 0 0 0 1000px green");
    }
});

现在感谢里格斯!