【问题标题】:getComputedStyle property valuesgetComputedStyle 属性值
【发布时间】: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(){ 上面的部分移到函数本身中。

标签: javascript css getcomputedstyle


【解决方案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
猜你喜欢
  • 2014-07-15
  • 2013-09-11
  • 2014-08-02
  • 1970-01-01
  • 2022-08-19
  • 2015-01-31
  • 1970-01-01
  • 2022-11-29
  • 2012-11-19
相关资源
最近更新 更多