获取样式 设置样式(访问行内样式)
- DOM 对象,style也是一个对象,封装了元素所有样式的属性,
- 样式名的写法,单个单词就是小写,如果是多个单词的样式(在CSS中用横线连接),从第二个单词开始首字母大写
- 通过style属性设置的样式,通常优先级会较高并且会直接在元素标签上有显示
- 使用style获取样式时,该样式必须是元素在行内样式添加过的
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#container{
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<div id="container" style="background: red;"></div>
</body>
<script type="text/javascript">
var container = document.getElementById('container');
container.onclick = function (){
this.getAttribute("style");
this.style;
this.style.backgroundColor = "blue";
this.style.width = "400px";
this.style.fontSize = "20px";
var bg = this.style.backgroundColor;
console.log(bg);
console.log(this.style.height);
}
</script>
</html>
2. 练习 点击开始按钮左边距++
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.bg{
height: 200px;
width: 200px;
background:red;
}
</style>
</head>
<body>
<div class="bg"></div>
<button id="btn1">开始</button>
<button id="btn2">停止</button>
</body>
<script type="text/javascript">
var bg = document.getElementsByClassName('bg')[0];
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
bg.style.marginLeft= "200px";
var intervalId ;
btn1.onclick = function (){
intervalId = setInterval(
function(){
if(parseInt(bg.style.marginLeft)>300){
clearInterval(intervalId);
return;
}
bg.style.marginLeft = parseInt(bg.style.marginLeft)+1+"px"
},30);
}
</script>
</html>
获取应用样式
- window.getComputedStyle(DOM对象,伪类)
- “伪类":可选,指定一个要匹配的伪元素的字符串。必须对普通元素省略(或 null)
- 获得网页元素== 最终起作用 ==的样式,返回值是一个对象,对象里面是样式的属性,属性值
- 得到的样式是只读的
- 注意获取特定样式的方法object[“marginLeft”];//双引号
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#container{
width: 200px;
height: 200px;
background: red;
margin-left: 10px;
}
</style>
</head>
<body>
<div id="container" style = "margin-left: 20px;"></div>
</body>
<script type="text/javascript">
var container = document.getElementById('container');
container.onclick = function (){
if(container.currentStyle){
console.log(container.currentStyle[marginLeft]);
return;
}
var objstyle = getComputedStyle(this);
console.log(objstyle["marginLeft"]);
}
</script>
</html>
style既可以获取,也可以设置
getComputedStyle只可以获取,不可以设置(只读)