ali*_*ali 11 javascript mouseover parent-child mouseout
我有这个小问题,我正在请求你的帮助.我有一个div元素,在其中我有一个img元素,就像这样
<div id="parent" onmouseover="MyFuncHover()" onmouseout="MyFuncOut()">
<img id="child" src="button.png" style="visibility: hidden" />
</div>
<script type="text/javascript">
function MyFuncHover() {
// Here I have some code that makes the "child" visible
}
function MyFuncOut() {
// Here I have some code that makes the "child" invisible again
}
</script>
Run Code Online (Sandbox Code Playgroud)
正如你所见,图像是div的孩子.我希望只有当我离开div时,孩子才会消失.然而,它看起来像当我将鼠标移动到图像时,MyFuncOut()函数被调用(因为,我想,我将鼠标悬停在图片离开DIV).我不希望这种情况发生.我想只在离开div区域时调用MyFuncOut()函数.
我不知道当你将鼠标移到子控件上时,它的父母会调用mouseout事件(即使我在孩子身上,我仍然在父母身上).我被困在这里,我需要你的一些好建议.谢谢!
变化
OK当我"抓出"孩子时,事件冒泡不会向父母发送"mouseout"事件.当我"鼠标悬停"孩子时,它也不会向父母发送"鼠标悬停"事件.那不是我需要的.当我"鼠标悬停"孩子时,我需要父母的"mouseout"事件不被发送.得到它?当我不希望将子项上的单击事件传播到父项时,事件冒泡很有用,但这不是我的情况.奇怪的是,当我"鼠标悬停"它们时,我在同一个父级中有其他元素不会触发父级的"mouseout"事件.
Vis*_*wda 24
你可以在jquery中使用"mouseenter"和"mouseleave"事件,这里是下面的代码,
$(document).ready(function () {
$("#parent").mouseenter(function () {
$("#child").show();
});
$("#parent").mouseleave(function () {
$("#child").hide();
});
});
Run Code Online (Sandbox Code Playgroud)
上面是附上一个事件,
<div id="parent">
<img id="child" src="button.png" style="display:none;" />
</div>
Run Code Online (Sandbox Code Playgroud)
您可以使用下面的解决方案,它是纯粹的JavaScript,我成功使用.
var container = document.getElementById("container");
var mouse = {x: 0, y: 0};
function mouseTracking(e) {
mouse.x = e.clientX || e.pageX;
mouse.y = e.clientY || e.pageY;
var containerRectangle = container.getBoundingClientRect();
if (mouse.x > containerRectangle.left && mouse.x < containerRectangle.right &&
mouse.y > containerRectangle.top && mouse.y < containerRectangle.bottom) {
// Mouse is inside container.
} else {
// Mouse is outside container.
}
}
document.onmousemove = function () {
if (document.addEventListener) {
document.addEventListener('mousemove', function (e) {
mouseTracking(e);
}, false);
} else if (document.attachEvent) {
// For IE8 and earlier versions.
mouseTracking(window.event);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望它有所帮助.