javascript - 为什么不返回 DOM 元素边框宽度?

标签 javascript css border

我只在 IE9 中尝试过,但我只收到一个空字符串 - 没有边框宽度。怎么了?!

<!DOCTYPE html><html><head>
<style type="text/css">
    .myCanvas {
        border-width: 2px;
        border-style: solid;
        border-color: red;
    }
</style>
</head><body>
    <div class="myCanvas">Something here</div>
    <script type="text/javascript">
        (function(){
            var borderWidth = document.getElementsByTagName('div')[0].style.borderWidth;
            console.log(borderWidth);
        })();
    </script>
</body>html>

最佳答案

style 对象仅包含存储在元素的 HTML style 属性中的数据。这里的元素没有 style 属性,更不用说其中的 border-width 声明了。这仅在您的标记如下所示时才有效:

<div class="myCanvas" style="border-width:2px">Something here</div>

2px

要提取计算的 CSS 样式,您需要使用 window.getComputedStyle() :

var div = document.getElementsByTagName('div')[0],
    borderWidth = window.getComputedStyle(div).borderWidth;
console.log(borderWidth);

2px

JSFiddle demo .

不幸的是,这不适用于 IE8,但适用于所有其他现代浏览器。 ( Browser Support )

关于javascript - 为什么不返回 DOM 元素边框宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21308042/

相关文章:

javascript - 将 div 定位到可见区域的中心

php - 对象方法不返回结果

html - 动态表格行高,同时忽略单元格中的内容高度

html - 跨越另一个 div 的 CSS 边框

html - CSS div 样式在 HTML 中不起作用

javascript - 仅使一部分可滚动而不是整个站点

javascript - 在 Chrome 扩展中写入本地文件系统

Javascript:求解方程组

CSS3 动画/过渡 webkit 问题

ios - 移除 UITabbar 上边框线