是否可以在jQuery中创建一个可以绑定到任何样式更改的事件侦听器?例如,如果我想在元素更改维度时"执行"某些操作,或者我可以执行样式属性中的任何其他更改:
$('div').bind('style', function() {
console.log($(this).css('height'));
});
$('div').height(100); // yields '100'
Run Code Online (Sandbox Code Playgroud)
这将非常有用.
有任何想法吗?
UPDATE
很抱歉自己回答这个问题,但我写了一个可能适合其他人的简洁解决方案:
(function() {
var ev = new $.Event('style'),
orig = $.fn.css;
$.fn.css = function() {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
})();
Run Code Online (Sandbox Code Playgroud)
这将临时覆盖内部prototype.css方法,并在最后用触发器重新定义它.它的工作原理如下:
$('p').bind('style', function(e) {
console.log( $(this).attr('style') );
});
$('p').width(100);
$('p').css('color','red');
Run Code Online (Sandbox Code Playgroud) 是否可以使用回调来监听 CSS 变量的变化?像这样:
documentElement.addListener('css-var-main-background-color', () => {
console.log('Value changed');
});
Run Code Online (Sandbox Code Playgroud)