如何通过DOMAttrModified检测类更改 [英] How to detect class changing by DOMAttrModified
问题描述
我需要检测一些类更改,我用于这个DOMAttrModified,但是有什么问题,什么?
I need to detect some class changing, i use for this DOMAttrModified, but something is wrong, what?
var first_img = $('body').find('li:first').find('img');
first_img.on('DOMAttrModified',function(e){
if (e.attrName === 'class') {
if ($(this).hasClass('current-image')) {
$(this).removeClass().addClass('previous-image');
}
console.log('log');
}
});
Thx for advice。
Thx for advice.
推荐答案
现在的问题是,一个 attrName
属性不是jQuery事件对象的一部分...您需要使用 e.originalEvent.attrName
。这是一个例子:
The immediate problem is that a attrName
property isn't part of jQuery's event's object...you need to use e.originalEvent.attrName
. Here's an example of it working:
var first_img = $("body").find("div").first();
first_img.on("DOMAttrModified", function (e) {
if (e.originalEvent.attrName === "class") {
console.log("##DOMAttrModified, class changed");
if ($(this).hasClass("current-image")) {
console.log("##Element has 'current-image' class, changing");
$(this).removeClass().addClass("previous-image");
}
}
});
setTimeout(function () {
first_img.addClass("current-image");
}, 1000);
演示: http://jsfiddle.net/R5rTy/1/
setTimeout
是模拟事件随机发生的。
The setTimeout
is to simulate the event randomly happening.
显然,所有浏览器都不支持 DOMAttrModified
事件 - http://help.dottoro.com/ljfvvdnm.php#additionalEvents
Apparently, the DOMAttrModified
event is not supported in all browsers - http://help.dottoro.com/ljfvvdnm.php#additionalEvents
更新:
使用较新的 MutationObserver
,下面显示了两种想法的使用:
Using the newer MutationObserver
, the following shows the use of both ideas:
var firstImg, observerConfig, firstImgObserver;
firstImg = $("body").find("div").first();
observerConfig = {
attributes: true,
childList: true,
characterData: true
};
firstImgObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var newVal = $(mutation.target).prop(mutation.attributeName);
if (mutation.attributeName === "class") {
console.log("MutationObserver class changed to", newVal);
} else if (mutation.attributeName === "id") {
console.log("MutationObserver id changed to", newVal);
}
});
});
firstImgObserver.observe(firstImg[0], observerConfig);
// later, you can stop observing
//observer.disconnect();
firstImg.on("DOMAttrModified", function (e) {
var newVal = $(this).prop(e.originalEvent.attrName);
console.log("DOMAttrModified", e.originalEvent.attrName, "changed to", newVal);
});
setTimeout(function () {
firstImg.addClass("previous-image").addClass("fdsa");
}, 1000);
演示: http://jsfiddle.net/ybGCF/
参考:
- https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
这篇关于如何通过DOMAttrModified检测类更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!