获取元素宽度的一个简单疑问
代码如果这么写,我们可以很正常的获取到div1元素的宽度
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function divwidth() {
var width = document.getElementById("div1").style.width;
alert(width);
}
</script>
</head>
<body >
<div id="div1" style="width:300px;height:500px;border:1px solid black"></div><br />
<input type="button" onclick="divwidth()" />
</body>
</html>
但是代码如果像下面这么写,我们就无法获取到div1元素的宽度,我想问问为什么
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
#div1
{
width:300px;
height:500px;
border:1px solid black;
}
</style>
<script type="text/javascript">
function divwidth() {
var width = document.getElementById("div1").style.width;
alert(width);
}
</script>
</head>
<body >
<div id="div1" ></div><br />
<input type="button" onclick="divwidth()" />
</body>
</html>
有劳各位大哥多多指教
------解决方案--------------------
HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
#div1
{
width:300px;
height:500px;
border:1px solid black;
}
</style>
<script type="text/javascript">
function getCss(obj, attr){
return obj.currentStyle? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr];
}
function divwidth() {
//var width = document.getElementById("div1").style.width; 这样是获取行内styel
//获取css里值这样写
var obj = document.getElementById("div1");
alert(getCss(obj, 'width'));
}
</script>
</head>
<body >
<div id="div1" ></div><br />
<input type="button" onclick="divwidth()" />
</body>
</html>