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

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

问题描述

是否可以在 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天全站免登陆