是否有可能在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');
jQuery csshook怎么样?
也许我不明白这个问题,但你正在搜索的东西很容易用cssHooks完成,不需要改变css()函数。
从文档中复制:
(function( $ ) {
// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
// If not, output an error message
throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}
// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
$.cssHooks[ "someCSSProp" ] = {
get: function( elem, computed, extra ) {
// Handle getting the CSS property
},
set: function( elem, value ) {
// Handle setting the CSS value
}
};
});
})( jQuery );
https://api.jquery.com/jQuery.cssHooks/
jQuery csshook怎么样?
也许我不明白这个问题,但你正在搜索的东西很容易用cssHooks完成,不需要改变css()函数。
从文档中复制:
(function( $ ) {
// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
// If not, output an error message
throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}
// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
$.cssHooks[ "someCSSProp" ] = {
get: function( elem, computed, extra ) {
// Handle getting the CSS property
},
set: function( elem, value ) {
// Handle setting the CSS value
}
};
});
})( jQuery );
https://api.jquery.com/jQuery.cssHooks/