在jQuery中是否有可能创建一个事件监听器,可以绑定到任何样式变化?例如,如果我想在元素尺寸发生变化或样式属性的任何其他更改时“执行”某些操作,我可以这样做:
$('div').bind('style', function() {
console.log($(this).css('height'));
});
$('div').height(100); // yields '100'
这将非常有用。
有什么想法吗?
更新
很抱歉自己回答了这个问题,但我写了一个好的解决方案,可能适合其他人:
(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');