编辑4: 现场演示
$(function() { $('#toggleColor').on('click', function() { $(this).toggleClass('darkblue'); }).attrchange({ trackValues: true, callback: function(event) { $(this).html("<ul><li><span>Attribute Name: </span>" + event.attributeName + "</li><li><span>Old Value: </span>" + event.oldValue + "</li><li><span>New Value: </span>" + event.newValue + "</li></ul>"); } });});body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 12px;}#toggleColor { height: 70px; width: 300px; padding: 5px; border: 1px solid #c2c2c2; background-color: #DBEAF9;}#toggleColor span { font-weight: bold;}#toggleColor.darkblue { background-color: #1A9ADA;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="http://meetselva.github.io/attrchange/javascripts/attrchange.js"></script><p>Click below div to toggle class darkblue.</p><div id="toggleColor"></div>
编辑3: 我把所有这些放在一起作为一个可以从git
attrchange下载的插件,这是[演示页面。
编辑2:
- 修复IE7和IE8中的propertName
编辑1:
- 处理多个元素
- 将条件排序为MutationObserver,DOMAttrModified和onpropertychange,以实现更好的实现。
向回调添加了修改后的属性名称。
$(function() {
(function($) {
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;function isDOMAttrModifiedSupported() { var p = document.createElement('p'); var flag = false; if (p.addEventListener) p.addEventListener('DOMAttrModified', function() { flag = true }, false); else if (p.attachEvent) p.attachEvent('onDOMAttrModified', function() { flag = true }); else return false; p.setAttribute('id', 'target'); return flag; } $.fn.attrchange = function(callback) { if (MutationObserver) { var options = { subtree: false, attributes: true }; var observer = new MutationObserver(function(mutations) { mutations.forEach(function(e) { callback.call(e.target, e.attributeName); }); }); return this.each(function() { observer.observe(this, options); }); } else if (isDOMAttrModifiedSupported()) { return this.on('DOMAttrModified', function(e) { callback.call(this, e.attrName); }); } else if ('onpropertychange' in document.body) { return this.on('propertychange', function(e) { callback.call(this, window.event.propertyName); }); } }})(jQuery);$('.test').attrchange(function(attrName) { alert('Attribute: ' + attrName + ' modified ');}).css('height', 100);
});
突变观察者是DOM4中突变事件的提议替代者。预计它们将包含在Firefox 14和Chrome 18中
浏览器支持:
onpropertychange-在IE中受支持(在IE 7中经过测试)
DOMAttrModified-在IE 9,FF和Opera中受支持
MutationObservers-是非常新的功能,在Chrome18中可以正常工作。不确定它支持多远,尚未在Safari中进行测试。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)