一款简单的监听 dom
宽高变化的监听器,记录下。
html
<div class="fake-element" style="height: 50px"></div>
css
.fake-element {
position: relative; /* 需要指定一个非 static 属性 */
100%;
}
.resize-observer {
position: absolute;
top: 0;
left: 0;
z-index: -1;
display: block;
100%;
height: 100%;
overflow: hidden;
pointer-events: none;
opacity: 0;
}
javascript
const userAgent = navigator.userAgent.toLowerCase();
const isIE = (userAgent.indexOf('trident') >= 0 || userAgent.indexOf('msie') >= 0);
const isEdge = (userAgent.indexOf('Edge/') >= 0);
const isEdgeOrIE = isIE || isEdge;
const resizeHandler = () => { console.log(new Date() };
const createResize = element => {
const obj = document.createElement('object');
obj.className = 'resize-observer';
obj.type = 'text/html';
obj.setAttribute('tabindex', '-1');
obj.setAttribute('aria-hidden', 'true');
obj.onload = () => {
const win = obj.contentDocument.defaultView;
win.onresize = _resizeHandler.bind(this);
};
// IE: Does not like that this happens before, even if it is also added after.
if (!isEdgeOrIE) { obj.data = 'about:blank' }
element.appendChild(obj);
// IE: This must occur after adding the object to the DOM.
if (isEdgeOrIE) { obj.data = 'about:blank' }
return obj;
};