检测文件高度变化 [英] Detect Document Height Change

查看:63
本文介绍了检测文件高度变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测我的文档的高度何时发生变化。完成后,我需要运行一些功能来帮助组织页面布局。

I'm trying to detect when my document height changes. Once it does, I need to run a few functions to help organize my page layout.

我不需要的是 window.onresize 。我需要比窗口大的整个文档。

I'm not looking for window.onresize. I need the entire document, which is larger than the window.

如何观察到这种变化?

推荐答案

尽管是 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'
})

这篇关于检测文件高度变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆