是否有可能在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');

当前回答

事情已经发生了一些变化,现在可以使用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'] });

传递给回调函数的参数是一个MutationRecord对象,它允许您获取旧样式值和新样式值。

支持良好的现代浏览器,包括IE 11+。

其他回答

正如其他人建议的那样,如果你可以控制任何改变元素样式的代码,你可以在改变元素高度时触发一个自定义事件:

$('#blah').bind('height-changed',function(){...});
...
$('#blah').css({height:'100px'});
$('#blah').trigger('height-changed');

否则,尽管相当耗费资源,但您可以设置一个计时器来定期检查元素高度的变化……

只是从上面添加并形式化了@David的解决方案:

请注意,jQuery函数是可链的,并返回'this',因此多个调用可以一个接一个地调用(例如$container.css("overflow", "hidden").css("outline", 0);)。

所以改进后的代码应该是:

(function() {
    var ev = new $.Event('style'),
        orig = $.fn.css;
    $.fn.css = function() {
        var ret = orig.apply(this, arguments);
        $(this).trigger(ev);
        return ret; // must include this
    }
})();

你可以尝试Jquery插件,它触发事件时,css是改变,它很容易使用

http://meetselva.github.io/#gist-section-attrchangeExtension

 $([selector]).attrchange({
  trackValues: true, 
  callback: function (e) {
    //console.log( '<p>Attribute <b>' + e.attributeName +'</b> changed from <b>' + e.oldValue +'</b> to <b>' + e.newValue +'</b></p>');
    //event.attributeName - Attribute Name
    //event.oldValue - Prev Value
    //event.newValue - New Value
  }
});

事情已经发生了一些变化,现在可以使用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'] });

传递给回调函数的参数是一个MutationRecord对象,它允许您获取旧样式值和新样式值。

支持良好的现代浏览器,包括IE 11+。

有趣的问题。问题是height()不接受回调,因此无法触发回调。使用animate()或css()设置高度,然后在回调中触发自定义事件。下面是一个使用animate()的例子,测试和工作(演示),作为概念的证明:

$('#test').bind('style', function() {
    alert($(this).css('height'));
});

$('#test').animate({height: 100},function(){
$(this).trigger('style');
});