2017-01-17 39 views
2

嗨,这是我的html结构。如何检测背景颜色改变的事件使用jQuery?

<div class="test-class" style="background-color: red;" >1</div> 
    <div class="test-class" style="background-color: blue;" >1</div> 
    <div class="test-class" style="background-color: green;" >1</div> 

这里在第一页加载测试类的背景颜色随机出现。

我想在测试类的背景颜色改变时运行一个函数。这个怎么做 ?

编辑

所以从Is it possible to listen to a "style change" event?这个问题,我有一个解决方案

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

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

但请大家帮忙申请这个答案。 我想提醒该div的内容,它的背景颜色改变时它是颜色。

+3

可能重复[是否有可能听到“风格变化”事件?](http://stackoverflow.com/questions/2157963/is-it-possible-to-listen-to-a-style-变化事件) –

回答

1

如果一些JavaScript更改背景颜色,您可以在更改背景后调用该函数吗?

+0

是的,这将是最好的方式来做到这一点。傻的做任何其他方式。您必须将原始值存储在变量中,并以设定的时间间隔将其与可能新的当前值进行比较......不值得头痛。 –

+0

如果我们无法检测到哪个事件会改变背景颜色,会发生什么?或者如果外部jquery文件在div的背景中进行更改。 –