如何使用Javascript获取继承的CSS值? [英] How can I get the inherited CSS value using Javascript?

查看:54
本文介绍了如何使用Javascript获取继承的CSS值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript获取继承的CSS属性的值。我找不到全面的答案。

I'm trying to get the value of an inherited CSS property using Javascript. I haven't been able to find a comprehensive answer.

CSS示例:

div {
    width: 80%;
}

示例加价:

<div id="mydiv"> Some text </div>

使用javascript(jQuery或native),我需要获得元素的宽度 - 不是以像素为单位,但字符串为80%。

Using javascript (jQuery, or native), I need to get the width of the element-- not in pixels, but the string "80%".

$('#mydiv').css('width'); // returns in px
$('#mydiv')[0].style.width // empty string
getComputedStyle($('#mydiv')[0]).width // returns in px

我需要将值作为字符串的原因是因为我需要将样式复制到另一个元素。如果它被声明为百分比,则另一个值必须是百分比。如果它在px中声明,则另一个值需要在px中。

The reason I need the value as a string is because I need to copy the style to another element. If it's declared as a percent, the other value needs to be a percent. If it's declared in px, the other value needs to be in px.

真正的技巧是该属性可以被继承,而不是在元素上显式声明(如我的例子。

The real trick is that this property could be inherited, not declared explicitly on the element (as in my example).

有没有人有任何想法?

推荐答案

没有办法得到我害怕的百分比值。您可以尝试这样的事情:

There's no way to get the percentage value I'm afraid. You can try something like this:

var widthpx = getComputedStyle($('#mydiv')[0]).width;
var parentWidth = $('#mydiv').parent().css('width')

var width = ( 100 * parseFloat(widthpx) / parseFloat(parentWidth) ) + '%';

这篇关于如何使用Javascript获取继承的CSS值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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