Article Directory
A, CSS style three
Previous DOM manipulation CSS inline styles , this one read write DOM CSS style sheets (internal and external style style referred to as a style sheet), be careful not to modify the style sheet
Two, DOM reads the CSS style sheet
2.1 attributes support IE
currentStyle property
- Syntax: element .currentStyle style name
- Role: Style Gets the element currently displayed
For example:
alert(box1.currentStyle.width);
2.2 Support other browsers (IE8 and below are not supported) method
getComputedStyle () method
- Parameter 1: need to obtain elements of style
- Parameter 2: passing a pseudo-element, generally pass null
- It returns the object that encapsulates the current style element
Role: window method can be used directly, to get the current style elements
For example:
alert(getComputedStyle(box1,null).width);
tips: The so-called support and do not support, there is no corresponding properties and methods of the browser
2.3 resolve browser compatibility issues
Approach: The above combination of properties and methods
Write a function integrated properties and methods
/**
* 定义一个函数,用来获取指定元素的当前样式
* 参数:
* - obj 要获取样式的元素
* - name 要获取的样式名
*/
function getStyle(obj,name){
if(window.getComputedStyle){
//正常浏览器的方式
return getComputedStyle(obj,null)[name];
}else{
//IE8的方式
return obj.currentStyle[name];
}
}
Variable (getComputedStyle) and attributes (window.getComputedStyle) the difference between :
- Variables: the need to find in scope, there is no error found
- Properties: not found returns undefined
Complete example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
<script type="text/javascript">
window.onload = function(){
//点击按钮以后读取box1的样式
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
//调用下面函数
var w = getStyle(box1,"width");
alert(w);
}
}
/**
* 定义一个函数,用来获取指定元素的当前样式
* 参数:
* - obj 要获取样式的元素
* - name 要获取的样式名
*/
function getStyle(obj,name){
//没有加window是一个变量,需要在作用域寻找
//变量没有找到报错,属性没有找到返回undefined
if(window.getComputedStyle){
//正常浏览器的方式
return getComputedStyle(obj,null)[name];
}else{
//IE8的方式
return obj.currentStyle[name];
}
}
</script>
</head>
<body>
<button id="btn01">点我一下</button>
<br/><br/>
<div id="box1"></div>
</body>
</html>
button button to get box1 style