简体   繁体   English

在没有轮询或突变观察者的情况下检测DIV高度的变化

[英]Detect when a DIV's height changes without polling or mutation observers

I need to get the height of a div and get notified when its height changes according to data. 我需要获得div的高度,并在其高度根据数据变化时得到通知。

I am using getBoundingClientRect() to get the height currently, but I don't get notified of any further changes. 我正在使用getBoundingClientRect()来获取当前的高度,但我没有得到任何进一步更改的通知。

I also tried DOMAttrModified and MutationObserver to detect changes in the data, but both of them are not universally supported in all browsers. 我还尝试使用DOMAttrModifiedMutationObserver来检测数据中的更改,但是并非所有浏览器都普遍支持这两种更改。

What's the best way to get notifications about changes to an element's height? 获取有关元素高度变化的通知的最佳方法是什么?

The idea (that seems to originate from a blog post on backalleycoder.com ) is that you can use 这个想法(似乎源于backalleycoder.com上博客文章 )是你可以使用的

  • onresize on the element itself in IE <=10. 在IE <= 10中对元素本身进行onresize
  • scroll events on a specially crafted <div> appended as a child of the element in most other browsers 在大多数其他浏览器中作为元素的子项附加的特制<div>scroll事件
  • or onresize on <object style="position: absolute; top: 0; left: 0; height: 100%; width: 100%;"> appended as a child of the element. onresize on <object style="position: absolute; top: 0; left: 0; height: 100%; width: 100%;">附加为元素的子元素。

There's a number of libraries that implement some or all of these approaches: 有许多库实现了部分或全部这些方法:

Note that older questions here on SO talk about: 请注意,SO上的旧问题谈到:

  • attrchange in jQuery, DOMAttrModified, etc. - that won't help you with detecting height changes that do not involve changing the height attribute jQuery,DOMAttrModified等中的attrchange - 这对于检测不涉及更改height属性的高度变化没有帮助
  • DOMSubtreeModified, MutationObserver - can be used to detect changes in content (which is one of the reasons that can lead to height changes -- the other being layout changes, such as a change to the width) DOMSubtreeModified,MutationObserver - 可用于检测内容的变化(这是导致高度变化的原因之一 - 另一个是布局变化,例如宽度的变化)
  • older solutions, including some jQuery plugins that use polling to accomplish this -- that's not a recommended solution, because the page will waste the user's battery even when nothing is resized. 较旧的解决方案,包括一些使用轮询来实现此目的的jQuery插件 - 这不是推荐的解决方案,因为即使没有调整大小,页面也会浪费用户的电池。

[edit] ResizeObserver will allow to detect this without hacks in newer browsers. [edit] ResizeObserver允许在没有新浏览器的黑客攻击的情况下检测到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM