DOM监听

resize事件只能加在window对象上,并不能监听具体某个DOM元素。

MutationObserver

监听DOM变动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function observeCHeader() {
var url = window.location.href;

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var observer = new MutationObserver(function() {
const cheaderId = url.split('cheaderId=')[1];

if (cheaderId) {
const id = cheaderId.split('#')[0];
const dom = document.getElementById(id);
if(dom) {
dom.classList.add('active');
}
}
});
observer.observe(document.querySelector('#header_nav'), {
childList: true,
attributes: true,
characterData: true,
subtree: true,
});
}

借助window 与 getBoundingClientRect

监听点击事件,点击之后打开。

1
2
// 点击出现弹出框,此处最好使用mousedown而非click
window.addEventListener('mousedown', this.close);

监听鼠标离开DOM

  1. 点击按钮,出现SiderBar(一个div)
  2. 鼠标在SiderBar(div)做操作。
  3. 当鼠标离开SiderBar(div)时,SiderBar应该消失。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class SideBar extends React.Component {
componentDidMount() {
window.addEventListener('mousemove', this.close);
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.close);
}
close = (e) => {
if (this.props.isOpen) {
const box = this.panel;
if (box) {
const boxBoundary = box.getBoundingClientRect();
const x = e.pageX;
const y = e.pageY;
const {
left, right, top, bottom,
} = boxBoundary;
const inBox = (
x > left &&
x <= right &&
y >= top &&
y <= bottom
);
if (!inBox) {
this.props.onLeave();
}
}
}
};
render() {
const { isOpen } = this.props;
return (
<div
ref={(div) => { this.panel = div; }}
className={`side-bar ${isOpen ? 'show' : 'hide'}`}
>
</div>
);
}
}
export default SideBar;

第三方工具

参考

  1. JS监听div元素的resize
-------------Keep It Simple Stupid-------------
0%