业务场景
- 在前端开发中,经常遇到需要判断鼠标落点是否在目标元素上;
- 记目标元素为XDom,则如果鼠标点到了XDom的子元素或者XDom本身,则认为鼠标在XDom上落下;
- 然后再执行下一步的逻辑。
解决方法
使用Node类上的方法contains
const XDom = document.createElement('div');
const parent = XDom.__proto__.__proto__.__proto__.__proto__;
parent.hasOwnProperty('contains'); // true
parent.constructor.name; // 'Node'
代码示例
handleMouseDown = (e) => {
if(!XDom.contains(e?.target)) return; // XDom是目标元素
// do something
}
注意事项
XDom.contains(XDom) === true;