练习地址:http://www.fgm.cc/learn/lesson4/05.html
获取css的属性:
- 行内样式:style.css直接获取
- 使用getComputedStyle获取对象之后,对象.属性或者对象[“属性”],我这里的写法类似
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css函数——设置/读取对象的属性</title>
<link rel="stylesheet" type="text/css" href="5_setReadAttr.css">
</head>
<body>
<div id="container">
<input type="button" value="Get Style">
<input type="button" value="Set Style">
<input type="button" value="Default Style">
</div>
<script type="text/javascript" src="5_setReadAttr.js"></script>
</body>
</html>
CSS1
div {
width: 400px;
height: 200px;
background-color: rgb(254,244,235);
border: 1px solid orange;
margin: 0 auto;
}
input {
color: white;
background: #FF9900;
border: none;
font-weight: bold;
margin: 10px 5px;
}
input:nth-of-type(1) {
margin-left: 20px;
}
CSS2
div {
width: 300px;
height: 100px;
background-color: rgb(239,248,255);
border: 1px solid #3399CC;
margin: 0 auto;
}
input {
color: white;
background: #3399CC;
border: none;
font-weight: bold;
margin: 10px 5px;
}
input:nth-of-type(1) {
margin-left: 20px;
}
JavaScript
window.onload = function() {
var input = document.getElementsByTagName("input");
var div = document.getElementsByTagName("div")[0];
var link = document.getElementsByTagName("link")[0];
// 通过改变导入样式的地址来改变样式
input[1].onclick = function() {
link.href = "5_setReadAttr2.css";
}
input[2].onclick = function() {
link.href = "5_setReadAttr.css";
}
input[0].onclick = function() {
// 这里直接获取样式hi行不通的,使用window.getComputedStyle也不行
var divStyle = document.defaultView.getComputedStyle(div);
divStyle.width == "400px"?
alert("width:400px;\nheight:200px;\nbackground-color:rgb(254,244,235)"):
alert("width:300px;\nheight:100px;\nbackground-color:rgb(239,248,255)");
}
};
孤独是人的本质。