更新时间:2023-02-26 15:07:13
尽管是 hack,但此简单功能会持续侦听目录。 (通过setTimeout)更改元素的高度并在检测到更改时触发回调。
Although a "hack", this simple function continuously "listens" (through setTimeout) to changes in an element's height and fire a callback when a change was detected.
重要的是要考虑元素的 height 可能会变化用户执行的任何操作(调整大小,点击等),因此,由于无法知道是什么会引起高度变化,因此可以完成所有操作绝对保证100%的检测是放置一个间隔高度检查器:
It's important to take into account an element's height might change regardless of any action taken by a user (resize, click, etc.) and so, since it is impossible to know what can cause a height change, all that can be done to absolutely guarantee 100% detection is to place an interval height checker :
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'
})