如何访问使用外部样式表的javascript对象的样式属性? [英] How can I access style properties on javascript objects which are using external style sheets?

查看:121
本文介绍了如何访问使用外部样式表的javascript对象的样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部样式表与此:

I have an external style sheet with this in it:

.box {
padding-left:30px;
background-color: #BBFF88;
border-width: 0;
overflow: hidden;
width: 400px;
height: 150px;
}

然后我有:

<div id="0" class="box" style="position: absolute; top: 20px; left: 20px;">

当我尝试访问div的宽度时:

When I then try to access the width of the div:

alert(document.getElementById("0").style.width);

出现一个空白警报框。
如何访问在我的样式表中定义的width属性?

A blank alert box comes up. How can I access the width property which is defined in my style sheet?

注意:div显示的宽度正确。

NOTE: The div displays with the correct width.

推荐答案

您应该使用 window.getComputedStyle 获取该值。我建议不要使用 offsetWidth clientWidth 如果你正在寻找CSS值,因为那些返回的宽度包括填充和其他计算。

You should use window.getComputedStyle to get that value. I would recommend against using offsetWidth or clientWidth if you're looking for the CSS value because those return a width which includes padding and other calculations.

使用 getComputedStyle ,您的代码将是:

var e = document.getElementById('0');
var w = document.defaultView.getComputedStyle(e,null).getPropertyValue("width");

此文档由MDC提供: window.getComputedStyle

The documentation for this is given at MDC : window.getComputedStyle

这篇关于如何访问使用外部样式表的javascript对象的样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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