JavaScript查看浏览器的计算样式
下面是演示代码
火狐浏览器使用
let styles = window.getComputedStyle(p, null);
谷歌浏览器使用
let styles = document.defaultView.getComputedStyle(p, null);
示例代码如下
- 1.样式表
.bgc-cyan {
background: brown;
}
.bgc-yellow {
background: yellow;
}
.border {
border-radius: 20px;
}
.center {
text-align: center;
line-height: 200px;
}
.width {
width: 200px;
}
.height {
height: 200px;
}
- 2.文档结构
<p>hello world</p>
- 3.使用JavaScript语法将样式添加到
p
标签上去
// 1.行内样式
const p = document.querySelector("P");
p.style.color = "lightskyblue";
console.log(p);
// 2.类样式
p.classList.add("bgc-cyan", "border", "center", "height", "width");
// 第一个参数是要查看样式的元素,第二个是伪元素
let styles = document.defaultView.getComputedStyle(p, null);
console.log(styles.getPropertyValue("height"));
console.log(styles.getPropertyValue("background-color"));
console.log(styles.getPropertyValue("color"));
console.log(styles.getPropertyValue("width"));
console.log(styles.getPropertyValue("height"));
console.log(styles.getPropertyValue("text-align"));