javascript - 检测文档高度变化

标签 javascript domdocument

我正在尝试检测我的 document 高度何时发生变化。完成后,我需要运行一些函数来帮助组织我的页面布局。

我不是在寻找 window.onresize。我需要整个文档,它比窗口大。

我如何观察这种变化?

最佳答案

更新(2020 年 10 月):

resizeObserver是一个很棒的 AP​​I ( 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'
})
LIVE DEMO

关于javascript - 检测文档高度变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866775/

相关文章:

javascript - Javascript和服务器之间的通信

php - 如何通过xpath从网站获取标题?

php - 无法读取 DOMDocument 中的元重定向 URL

java - 使用java中的Document删除xml中的节点

PHP 和 DOMDocument removeNode 留下空行

domdocument - PHP 命令行脚本忽略 php.ini 和 ini_set ('memory_limit' ,...) 指令

javascript - D3 轴刻度硬计数

javascript - 设置 asp :RadioButton Text from javascript

javascript - 编译在线 html 表单上提交的代码并使用 gcc 处理它的过程

javascript - 从 Canvas 像素数据中获取错误的 RGB 值