getComputedStyle 属性值

Posted

技术标签:

【中文标题】getComputedStyle 属性值【英文标题】:getComputedStyle property values 【发布时间】:2015-12-21 15:13:53 【问题描述】:

我正在尝试报告我创建的椭圆形 div 的边框半径的值,但我得到了一个未定义的返回值。谁能解释为什么?我犯了一个简单的错误还是我的代码有问题?谢谢!

<!DOCSTYLE html>
<html>
<head>
    <title>CSS3</title>
    <style>
        #oval
            width: 500px;
            height: 300px;
            background: black;
            border-bottom-left-radius: 50%;
            border-bottom-right-radius: 50%;
            border-top-left-radius: 50%;
            border-top-right-radius: 50%;
        
    </style>
    <script>
        var myOval = document.getElementById('oval');
        var bRadBL = window.getComputedStyle(myOval).getPropertyValue("border-bottom-left-radius");
        var bRadBR = window.getComputedStyle(myOval).getPropertyValue("border-bottom-right-radius");
        var bRadTL = window.getComputedStyle(myOval).getPropertyValue("border-top-left-radius");
        var bRadTR = window.getComputedStyle(myOval).getPropertyValue("border-top-right-radius");
        var bRad = getComputedStyle(myOval).getPropertyValue("borderRadius");
        function compStyle()
            alert("Top Left Radius: "+bRadTL+"\nBottom Left Radius: "+bRadBL+"\nTop Right Radius: "+bRadTR+"\nBottom Right Radius: "+bRadBR);
     
    </script>
</head>
<body>
    <div id="oval"></div>
    <input type="button" value="click me" onClick="compStyle()"/>
</body>
</html>

编辑:我尝试了“border-bottom-left-radius”和“borderBottomLeftRadius”,结果相同。我应该使用哪一个?

【问题讨论】:

你的脚本在元素存在之前就被执行了。将function compStyle() 上面的部分移到函数本身中。 【参考方案1】:

在渲染元素之前运行脚本。在声明 html 元素 id 之后,将脚本块移动到正文的末尾:

#oval
  width: 500px;
  height: 300px;
  background: black;;
  border-bottom-left-radius: 50%;
  border-bottom-right-radius: 50%;
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
<div id="oval"></div>
<input type="button" value="click me" onClick="compStyle()"/>

<script>
  var myOval = document.getElementById('oval');
  var bRadBL = window.getComputedStyle(myOval).getPropertyValue("border-bottom-left-radius");
  var bRadBR = window.getComputedStyle(myOval).getPropertyValue("border-bottom-right-radius");
  var bRadTL = window.getComputedStyle(myOval).getPropertyValue("border-top-left-radius");
  var bRadTR = window.getComputedStyle(myOval).getPropertyValue("border-top-right-radius");
  var bRad = getComputedStyle(myOval).getPropertyValue("borderRadius");
  function compStyle()
    alert("Top Left Radius: "+bRadTL+"\nBottom Left Radius: "+bRadBL+"\nTop Right Radius: "+bRadTR+"\nBottom Right Radius: "+bRadBR);
  
</script>

【讨论】:

嘿,谢谢!我一定错过了教科书中解释这一点的部分。虽然我确定我没有,而且这是一本糟糕的教科书(任何能让我感觉自己是一个更好的程序员并且晚上睡得更好的东西)。再次感谢! 哈哈。这是基础知识,所以如果这本书不包含它,那就放弃这本书。无论如何,也许这本书提到了这个method。

以上是关于getComputedStyle 属性值的主要内容,如果未能解决你的问题,请参考以下文章

用JS获取CSS中的某个属性值:getComputedStyle

JS使用getComputedStyle()方法获取CSS属性值

JS使用getComputedStyle()方法获取CSS属性值

JS使用getComputedStyle()方法获取CSS属性值

JavaScript getComputedStyle

getComputedStyle方法的那些事