ts.*_*ts. 62 javascript jquery events dom dom-events
是否有任何方法可以触发属性更改事件(可能是自定义)?
让我们说,当IMG src被改变或DIV的innerHtml?
小智 51
注意:截至2012年,Mutation Events已从标准中删除,现已弃用.有关如何使用其替代品,请参阅其他答案或文档MutationObserver
.
您指的是DOM Mutation Events.这些事件的浏览器支持很差(但正在改进).jQuery的Mutation Events插件可能会让你有所帮助.
Mat*_*ats 40
如何设置MutationObserver,主要是从MDN复制的,但为了清楚起见,我添加了自己的注释.
window.MutationObserver = window.MutationObserver
|| window.WebKitMutationObserver
|| window.MozMutationObserver;
// Find the element that you want to "watch"
var target = document.querySelector('img'),
// create an observer instance
observer = new MutationObserver(function(mutation) {
/** this is the callback where you
do what you need to do.
The argument is an array of MutationRecords where the affected attribute is
named "attributeName". There is a few other properties in a record
but I'll let you work it out yourself.
**/
}),
// configuration of the observer:
config = {
attributes: true // this is to watch for attribute changes.
};
// pass in the element you wanna watch as well as the options
observer.observe(target, config);
// later, you can stop observing
// observer.disconnect();
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
如果您只需要特定的东西,那么setInterval()
通过每隔几毫秒检查一次目标属性就可以使用简单的东西:
var imgSrc = null;
setInterval(function () {
var newImgSrc = $("#myImg").attr("src");
if (newImgSrc !== imgSrc) {
imgSrc = newImgSrc;
$("#myImg").trigger("srcChange");
}
}, 50);
Run Code Online (Sandbox Code Playgroud)
然后绑定到自定义"srcChange"事件:
$("#myImg").bind("srcChange", function () {....});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63301 次 |
最近记录: |