javascript - CSS样式在JavaScript中输出空字符串

标签 javascript css

我正在尝试获取 JavaScript 中元素的 padding 值。方法如下:

var textWrapper = document.getElementById('textWrapper');
console.log(textWrapper.children[0].style.padding);

它输出一个空字符串,即使在 css 样式中,padding 设置为 10px。我做错了什么,我该如何解决?

JSFiddle

console.clear()

var textWrapper = document.getElementById('textWrapper');
console.log(textWrapper.children[0].style.padding);
.text {
  width: 200px;
  height: 50px;
  padding: 10px;
}
<div id="textWrapper">
  <div class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do</div>
  <div class="text">Duis aute irure dolor in reprehenderit</div>
  <div class="text">Excepteur sint occaecat cupidatat non</div>
  <div class="text">"Sed ut perspiciatis unde omnis iste natus error sit</div>
</div>

最佳答案

.style 属性获取内联 CSS。使用 getComputedStyle()相反。

el = document.getElementById('textWrapper')
style = window.getComputedStyle(el)
padding = style.getPropertyValue('padding')

关于javascript - CSS样式在JavaScript中输出空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196349/

相关文章:

javascript - Cucumber.js 和资源

javascript - 如何将自定义 HTML 添加到 ngx Typeahead?

javascript - 如何在第一个和最后一个列表项处停止切换功能?

javascript - 点击时更改颜色的铁图标

javascript - JavaScript 中类似警报的函数

javascript - 请提供更多帮助让这个循环正常工作?

javascript - 如何在 Firebase 中获取 Unix 时间戳?

html - 如何在 Vim 每次保存 "source file"时自动更新或压缩 CSS、JS 和 HTML 文件?

html - 如何在 Polymer 1.0 中创建 2 列布局?

html - 修复困惑的 css 以在标签旁边显示复选框