Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

任何支持 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)"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.