是否可以在 jQuery 中创建一个可以绑定到任何样式更改的事件侦听器?例如,如果我想在元素更改尺寸或样式属性中的任何其他更改时“执行”某些操作,我可以执行以下操作:
$('div').bind('style', function() {
console.log($(this).css('height'));
});
$('div').height(100); // yields '100'
这真的很有用。
有任何想法吗?
UPDATE
很抱歉自己回答这个问题,但我写了一个可能适合其他人的简洁解决方案:
(function() {
var ev = new $.Event('style'),
orig = $.fn.css;
$.fn.css = function() {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
})();
这将临时覆盖内部prototype.css方法并在最后使用触发器重新定义它。所以它的工作原理是这样的:
$('p').bind('style', function(e) {
console.log( $(this).attr('style') );
});
$('p').width(100);
$('p').css('color','red');
自从提出问题以来,事情发生了一些变化 - 现在可以使用变异观察者 https://developer.mozilla.org/en/docs/Web/API/MutationObserver检测元素“style”属性的变化,不需要 jQuery:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
console.log('style changed!');
});
});
var target = document.getElementById('myId');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });
传递给回调函数的参数是突变记录 https://developer.mozilla.org/en/docs/Web/API/MutationObserver#MutationRecord允许您获取旧样式值和新样式值的对象。
支持的是在现代浏览器中表现良好 http://caniuse.com/mutationobserver包括 IE 11+。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)