我在绝对定位的div中的onmouseout函数遇到了麻烦。当鼠标击中div中的子元素时,mouseout事件发生,但我不希望它发生,直到鼠标离开父元素,绝对div。
我如何防止mouseout事件从发射时,它击中一个子元素没有jquery。
我知道这与事件冒泡有关,但我没有找到如何解决这个问题的方法。
我在这里找到了一个类似的帖子:如何禁用由子元素触发的鼠标退出事件?
但是,该解决方案使用jQuery。
我在绝对定位的div中的onmouseout函数遇到了麻烦。当鼠标击中div中的子元素时,mouseout事件发生,但我不希望它发生,直到鼠标离开父元素,绝对div。
我如何防止mouseout事件从发射时,它击中一个子元素没有jquery。
我知道这与事件冒泡有关,但我没有找到如何解决这个问题的方法。
我在这里找到了一个类似的帖子:如何禁用由子元素触发的鼠标退出事件?
但是,该解决方案使用jQuery。
当前回答
用onmouseleave代替onmouseout。
你还没有向我们展示你的具体代码,所以我不能在你的具体例子中告诉你如何做到这一点。
但是它很简单:用onmouseleave代替onmouseout。
就是这样:)所以,很简单:)
如果不知道怎么做,请参阅解释:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove_leave_out
和平的蛋糕:)尽情享受吧。
其他回答
尝试mouseleave ()
例子:
<div id="parent" mouseleave="function">
<div id="child">
</div>
</div>
;)
我认为Quirksmode有你需要的所有答案(不同的浏览器冒泡行为和mouseenter/mouseleave事件),但我认为最常见的结论是,事件冒泡混乱的使用框架,如JQuery或Mootools(有mouseenter和mouseleave事件,这正是你直觉会发生的)。
看看他们是怎么做的,如果你想的话,自己做吧 或者你也可以用事件部分(及其依赖项)创建自定义的“精益”版本的Mootools。
有一个简单的方法可以让它起作用。元素和所有子元素都设置了相同的类名,那么:
element.onmouseover = function(event){
if (event.target.className == "name"){
/*code*/
}
}
在Angular 5、6和7上
<div (mouseout)="onMouseOut($event)"
(mouseenter)="onMouseEnter($event)"></div>
然后在
import {Component,Renderer2} from '@angular/core';
...
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit, OnDestroy {
...
public targetElement: HTMLElement;
constructor(private _renderer: Renderer2) {
}
ngOnInit(): void {
}
ngOnDestroy(): void {
//Maybe reset the targetElement
}
public onMouseEnter(event): void {
this.targetElement = event.target || event.srcElement;
console.log('Mouse Enter', this.targetElement);
}
public onMouseOut(event): void {
const elementRelated = event.toElement || event.relatedTarget;
if (this.targetElement.contains(elementRelated)) {
return;
}
console.log('Mouse Out');
}
}
如果你添加(或拥有)一个CSS类或id到父元素,那么你可以这样做:
<div id="parent">
<div>
</div>
</div>
JavaScript:
document.getElementById("parent").onmouseout = function(e) {
e = e ? e : window.event //For IE
if(e.target.id == "parent") {
//Do your stuff
}
}
所以只有当事件在父div上时,才会执行东西。