Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 90 期(JavaScript-DOM):获取DOM的样式 #93

Open
wingmeng opened this issue Aug 19, 2019 · 0 comments
Open

第 90 期(JavaScript-DOM):获取DOM的样式 #93

wingmeng opened this issue Aug 19, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

任何支持 style 特性的 HTML 元素在 JavaScript 中都有一个对应的 style 属性,对于使用短横线连接的 CSS 属性名,则需要将其转为驼峰大小写形式,才能通过 JavaScript 访问。

举例:

CSS 属性 JavaScript 属性
background-color style.backgroundColor
display style.display
font-family style.fontFamily

注意:CSS 中的 float 属性,在 JavaScript 中对应的属性名是 cssFloat,IE 中则是 styleFloat

获取 style 中的样式:

#myDiv {
  color: #000 !important;
  border: 1px solid blue;
}
<div id="myDiv" style="font-size:20px; color:red"></div>
var myDiv = document.getElementById('myDiv');

myDiv.style.fontSize;  // "20px"
myDiv.style.color;  // "red"
myDiv.style.border;  // ""
myDiv.style.cssText;  // "font-size: 20px; color: red;"

获取计算的样式:

虽然 style 对象能提供支持 style 特性的任何元素的样式信息,但它不包含那些从其他样式表层叠而来并影响到当前元素的样式信息。要获取这类计算后的样式,需要用到 getComputedStyle 方法。

语法:window.getComputedStyle(element [, pseudoElt ])

var computedStyle = window.getComputedStyle(myDiv);

console.log(computedStyle.color);  // "rgb(0, 0, 0)"
console.log(computedStyle.fontSize);  // "20px"
console.log(computedStyle.border);  // "1px solid rgb(0, 0, 255)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant