我正在尝试检测我的 document
高度何时发生变化。完成后,我需要运行一些函数来帮助组织我的页面布局。
我不是在寻找 window.onresize
。我需要整个文档,它比窗口大。
我如何观察这种变化?
最佳答案
更新(2020 年 10 月):
resizeObserver是一个很棒的 API ( support table )
// create an Observer instance
const resizeObserver = new ResizeObserver(entries =>
console.log('Body height changed:', entries[0].target.clientHeight)
)
// start observing a DOM node
resizeObserver.observe(document.body)
// click anywhere to rnadomize height
window.addEventListener('click', () =>
document.body.style.height = Math.floor((Math.random() * 5000) + 1) + 'px'
)
click anywhere to change the height
旧答案:
尽管是“hack”,这个简单的函数会持续“监听”(通过 setTimeout)元素高度的变化,并在检测到变化时触发回调。
重要的是要考虑到元素的高度可能会发生变化,无论用户采取什么操作(调整大小、点击等)。 ) 等等,因为不可能知道什么会导致高度变化,所以为了绝对保证 100% 检测,可以做的就是放置一个间隔高度检查器:
function onElementHeightChange(elm, callback) {
var lastHeight = elm.clientHeight, newHeight;
(function run() {
newHeight = elm.clientHeight;
if (lastHeight != newHeight)
callback(newHeight)
lastHeight = newHeight
if (elm.onElementHeightChangeTimer)
clearTimeout(elm.onElementHeightChangeTimer)
elm.onElementHeightChangeTimer = setTimeout(run, 200)
})()
}
// to clear the timer use:
// clearTimeout(document.body.onElementHeightChangeTimer);
// DEMO:
document.write("click anywhere to change the height")
onElementHeightChange(document.body, function(h) {
console.log('Body height changed:', h)
})
window.addEventListener('click', function() {
document.body.style.height = Math.floor((Math.random() * 5000) + 1) + 'px'
})
关于javascript - 检测文档高度变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866775/