2

I know this sounds simple, but here's what i got that's not working.

<style type="text/css">#graphelement{width:800px;height:300px;}</style>
<div id="graphlabel2">Right Axis Label</div>
<div id="graphelement"></div>

<script type="text/javascript">
var graphwidth = document.getElementById('graphelement').style.width;
document.getElementById('graphlabel2').style.width = graphwidth;
</script>

My problem is that 'graphwidth' always comes up empty. If i just grab the element's width (element.width), i get 'undefined' in 'graphwidth. All code above is within the body tag, even the initial style tag.

This is part of a larger script, but i can figure the rest out if i can get a width from and element and set it to another. My overall goal: i have an element whose width is set in inline styles. If the page is viewed on a handheld (i.e., screen width is smaller than graphwidth), then i want to set the width of the element and associated elements to screen.width. I seem to be having trouble retrieving and setting element.style.width though.

4

4 回答 4

4

style.width一个元素是空的,除非你通过 javascript 分配它。相反,你想要的是computedStyle. 这是一些文档

window.getComputedStyle(document.getElementById('graphelement').width).

请注意,旧版本的 IE 使用currentStyle. (看来只有 IE9+ 支持 getComputedStyle) document.getElementById('graphelement').currentStyle.width

这是一个jsFiddle演示如何支持两者。

于 2012-05-17T20:36:29.320 回答
3

我认为您需要使用window.getComputedStyle()

var gLabel = document.getElementById("graphelement");
var style = window.getComputedStyle(gLabel , null);

document.getElementById('graphlabel2').style.width = style.getPropertyValue("height");
于 2012-05-17T20:37:00.960 回答
0

.style 属性用于获取直接放置在元素上的样式。它不会从您的样式表中计算样式。

请参考: 为什么 javascript this.style[property] 返回一个空字符串?

于 2012-05-17T20:42:10.447 回答
0

使用document.getElementById,您无法获取 css 值,只能设置它们。

我想就是你要找的。

于 2012-05-17T20:35:23.937 回答