Javascript元素样式 [英] Javascript element style

查看:67
本文介绍了Javascript元素样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么这个

<div class = "overlay">
    fdsfsd
</div>
.overlay{
    width: 100px;
    height: 200px;
    background-color:red;
}
alert(document.getElementsByClassName("overlay")[0].style.width); 

没有提醒任何事情。当然我可以写< div style =width:100px>
然后everthing工作正常,但它对我不好,我需要css 。
在这里你可以找到一个 jsfiddle demo

is not alerting nothing. Of course I can write <div style = "width:100px"> then everthing works fine, but it is not good for me, I need css. Here you can find a jsfiddle demo

所以确切的问题是:为什么这段代码没有警告div的宽度以及如果宽度由css给出时如何警告?

So exact question is: why this code is not alerting width of div and how alert it if width is given by css?

推荐答案

JavaScript .style 仅与元素上的内联样式有关。

The JavaScript .style only relates to inline styles on the element.

请参阅文档

如果你想获得元素的宽度,你应该使用 offsetWidth

If you want to get the width of an element you should use offsetWidth.

document.getElementsByClassName("overlay")[0].offsetWidth

http://jsfiddle.net/9kwap3zy/7/

这篇关于Javascript元素样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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