是否有可能收听“风格改变”事件?
2022-08-30 00:43:20
是否可以在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);
}
})();
这将临时覆盖内部原型.css方法,并在末尾使用触发器重新定义它。所以它的工作原理是这样的:
$('p').bind('style', function(e) {
console.log( $(this).attr('style') );
});
$('p').width(100);
$('p').css('color','red');