如何将样式表元素的值分配给变量


How do I assign the value of a stylesheet element to a variable?

我在点击链接时调整了div的大小,但我真的需要将值分配给一个变量,之后我可以改变值…最终拥有[+]和[-]按钮,允许用户每次增加和减少1像素的大小。

目前我只是想让"framewidth"获取样式表宽度的值,然后在屏幕上打印该值…一旦我知道了这个值,我就可以使用它了。

我读了几十篇文章,花了10多个小时在这上面,这就是我到目前为止所知道的…

(我讨厌成为一个新手lol)

"resize.php"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <link rel="stylesheet" href="resize.css" type="text/css"/>
 <title>Resize</title>
</head>
<body>
<script type="text/javascript">
function frame700()
{
 var framewidth=document.getElementById('frame').style.width.value;
 document.getElementById('frame').style.width='700px';
 document.getElementById("info").innerHTML=framewidth;
}
function frame500()
{
 document.getElementById('frame').style.width='500px';
}
</script>
<div class="resize" ID="frame" style="width:500px"> 
 <table>
 <tr>
  <td>
   <a href="#" onclick="frame700()">700</a> <a href="#" onclick="frame500()">500</a><br/>
  </td>
 </tr>
 <tr>
  <td id="info"></td>
 </tr>
</table> 
</div>
</body>
</html>
"resize.css"

div.resize
{
 position:absolute;
 height:100px;
 background-color:#ffc080;
 border:2px solid orange;
}

.style.width将为您提供元素的宽度,它没有.value属性。

应该是

var framewidth = document.getElementById('frame').style.width;

演示:小提琴


您可能还想看看window.getComputedStyle()

function frame700() {
    var el = document.getElementById('frame'),
        style = window.getComputedStyle ? window.getComputedStyle(el) : el.currentStyle || {};
    var framewidth = style.width;
    document.getElementById('frame').style.width = '700px';
    document.getElementById("info").innerHTML = framewidth;
}

演示:小提琴