开发者

Get calculated opacity of element with jQuery

开发者 https://www.devze.com 2023-01-04 00:58 出处:网络
Is there a way in jQuery to get the true opacity of an element? You can, of course, get the element\'s defined opacity with开发者_运维百科

Is there a way in jQuery to get the true opacity of an element? You can, of course, get the element's defined opacity with

开发者_运维百科
$element.css('opacity')

but if, say, its parent has defined opacity 0.5, then the element's true opacity is half of what its defined opacity is. Does jQuery have a function for this? If not, is there an existing plugin?

If there isn't a plugin, could I calculate this myself by iterating over the element's parents until I finally reach the top-most parent, multiplying the CSS opacity each step of the way? Or is there something I'm not taking into account?


Doesn't look like there's a quick property that checks that, but you can easily calculate it, as you've mentioned:

var opacity = 1;
$element.parents().andSelf()
        .each(function(){ opacity *= $(this).css('opacity') || 1 });

The only edge case I can think of is if the element is hidden, or is partially hidden by a floating element (that isn't its parent). Depending on what you need it may be a problem.

Working example: http://jsbin.com/okase/2

0

精彩评论

暂无评论...
验证码 换一张
取 消