是否有可能倾听“风格变化”。事件? [英] Is it possible to listen to a "style change" event?

查看:85
本文介绍了是否有可能倾听“风格变化”。事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在jQuery中创建一个可以绑定到任何样式更改的事件侦听器?例如,如果我想在元素更改尺寸时做某事,或者我可以执行样式属性中的任何其他更改:

Is it possible to create an event listener in jQuery that can be bound to any style changes? For example, if I want to "do" something when an element changes dimensions, or any other changes in the style attribute I could do:

$('div').bind('style', function() {
    console.log($(this).css('height'));
});

$('div').height(100); // yields '100'

这将非常有用。

有任何想法吗?

更新

很抱歉回答我自己,但我写了一个可能适合其他人的整洁解决方案:

Sorry for answering this myself, but I wrote a neat solution that might fit someone else:

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

这将临时覆盖内部prototype.css方法,并在最后用触发器重新定义它。所以它的工作原理如下:

This will temporary override the internal prototype.css method and the redefine it with a trigger at the end. So it works like this:

$('p').bind('style', function(e) {
    console.log( $(this).attr('style') );
});

$('p').width(100);
$('p').css('color','red');


推荐答案

由于jQuery是开源的,我猜想您可以调整 css 函数,以便在每次调用时调用您选择的函数(传递jQuery对象)。当然,您需要搜索jQuery代码以确保其内部没有任何其他内容用于设置CSS属性。理想情况下,你想为jQuery编写一个单独的插件,这样它就不会干扰jQuery库本身,但是你必须决定它对你的项目是否可行。

Since jQuery is open-source, I would guess that you could tweak the css function to call a function of your choice every time it is invoked (passing the jQuery object). Of course, you'll want to scour the jQuery code to make sure there is nothing else it uses internally to set CSS properties. Ideally, you'd want to write a separate plugin for jQuery so that it does not interfere with the jQuery library itself, but you'll have to decide whether or not that is feasible for your project.

这篇关于是否有可能倾听“风格变化”。事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆