【问题标题】:Observe implicit size changes on HTMLElements观察 HTMLElements 上的隐式大小变化
【发布时间】:2018-10-08 06:27:41
【问题描述】:

虽然 MutationObserver 允许监视 HTMLElement 属性的显式大小更改,但它似乎没有一种方法/配置可以让我监视 implicit 对其大小的更改,这些更改由浏览器。

这是一个例子:

const observer = new MutationObserver(changes => {
  console.log('changed')
})

observer.observe(document.querySelector('#bar'), {
  attributes: true
})

document.querySelector('#foo').style.width = '200px'
.container {
  display: flex;
  align-items: stretch;
}

.child {
  width: 100px;
  height: 100px;
  margin: 0 2px;
  background: magenta;
}
<div class="container">
  <div class="child" id="foo"></div>
  <div class="child" id="bar"></div>
</div>

在上面的示例中,我正在更改#foo 的大小,同时观察#bar#bar#foo 压扁(它的宽度隐式变化,因为浏览器计算了它的宽度,而不是我明确指定它)。

如何检测这种隐式大小变化?

【问题讨论】:

标签: javascript mutation-observers


【解决方案1】:

...但是,调整大小事件仅在窗口对象上触发(发送到) :: MDN

新标准是::Resize Observer

new ResizeObserver(()=>console.log('bar dimension changed :: RO!')).observe(bar);

但是虽然它仅适用于晚期 Chrome,但我建议使用一些库,例如: CSS-Element-Queries

<script src="css-element-queries-1.0.0/src/ResizeSensor.js"></script>
<script src="css-element-queries-1.0.0/src/ElementQueries.js"></script>
new ResizeSensor(bar, function(){ 
    console.log('bar dimension changed :: CSS-Element-Queries');
});

【讨论】:

  • 我担心 ResizeSensor 和/或 ElementQueries 会使用轮询来确定它是否发生了变化,这将不利于性能。你知道他们用什么方法来确定变化吗?
  • 两者都是基于事件的。
  • 元素调整大小时会触发哪个事件?如果是这样,我就不能在不使用库的情况下自己拿起它吗?
  • ResizeObserver 是浏​​览器内部技术。可从 Chrome 64(?) 获得。 Css-Element-Query 正在使用 requestAnimationFrame 并迭代整个 DOM 树
【解决方案2】:

Hi just take the javascript part to the end of the body

<!DOCTYPE HTML>
<html>
<head>
    <style>
        .container {
            display: flex;
            align-items: stretch;
            
        }

        .child {
            width: 200px;
            height: 100px;
            margin: 0 2px;
            background: magenta;
        }
       
    </style>
   
</head>

<body onload="">

    <div class="container">
        <div class="child" id="foo"></div>
        <div class="child" id="bar"></div>
    </div>
    <script>
        const observer = new MutationObserver(changes => {
            console.log('changed')
        });

        observer.observe(document.querySelector('#bar'), {
            attributes: true
        });

        document.querySelector('#foo').style.width = '400px'
    </script>
</body>
</html>

【讨论】:

  • 我认为你不明白我的问题是什么。
  • 根据观察#bar。 #bar get 被 #foo 压扁了,我还是改了
  • 对不起,没有。你的答案是完全错误的。这与脚本加载问题无关。同样在您所谓的“固定”示例中,回调不会触发。
猜你喜欢
  • 2020-03-21
  • 2018-12-15
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 2010-11-09
  • 2018-02-26
  • 2015-09-13
  • 1970-01-01
相关资源
最近更新 更多