使用Javascript跟踪HTML元素上的显示更改 [英] Track display changes on HTML element with Javascript

查看:110
本文介绍了使用Javascript跟踪HTML元素上的显示更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个给定的HTML元素,例如:

Suppose I have a given HTML element, such as:

<div id="foo">...</div>

在该元素的内部,可能会发生很多事情,这会改变该元素的一些显示配置,例如高度或固定位置。

Inside that element, lots of things can happen that will change some display configurations of that element, like its height or fixed position.

有没有可以跟踪与该元素的显示相关的任何更改?当元素更改任何显示变量时,是否有一般的事件触发?

Is there anyway I can track any changes related to the display of that element? Is there a general event that gets fired when the element changes any display variable?

推荐答案

只需使用以下内容:

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // Use of the information here.
});

observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

在调用 MutationObserver 对于事件,并获得变量变量列表。

In the call to MutationObserver you can listen to the events and get the list of elements changed in variable mutations.

observer.observe 的第一个参数中你可以设置要监听的元素。在同一个方法的第二个参数中,您可以设置要收听的内容。

In the first argument to observer.observe you can set the elements to listen. In the second argument to the same method you can set what you want to listen.

此代码适用于Chrome,Firefox和Safari。使用其他浏览器,您可以使用事件,例如'DOMAttrModified''propertychange',如果你想只是请参阅修改的属性,例如

This code works with Chrome, Firefox and Safari. With the others browsers you can use events, such as 'DOMAttrModified' and 'propertychange', if you want to just see attributes modified, in example.

祝你好运。

这篇关于使用Javascript跟踪HTML元素上的显示更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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