1. style
通过 DOM 元素对象的 style 属性,只能获取元素的行内样式,没有设置则获取不到,也可以通过它来改变行内样式。
var box = document.getElementById('box');
box.style.color // 读取,没有设置则返回 "" 空字符串
box.style.color = 'red'; // 修改
通过元素的 style
属性获取的是 CSSStyleDeclaration 对象
2. getComputedStyle()
getComputedStyle
可以获取当前元素所有最终使用的 CSS 属性值
接受两个参数:
element: 要取得计算样式的元素对象
pseudoElt: 伪元素字符串(例如“:before”) 。如果不需要伪元素信息,第二个参数可以省略或设置为 null
window.getComputedStyle(element [,pseudoElt ]);
//=> 第二种用法
document.defaultView.getComputedStyle(element [,pseudoElt ]);
返回的是一个活动 CSSStyleDeclaration对象,它在元素的样式更改时自动更新。
虽然与从元素的 style
属性返回的对象具有相同的类型,但是从 getComputedStyle
返回的对象是只读的
这个对象中的 CSS 属性值可以使用 getPropertyValue(propName)
或直接索引到对象,如 cs ['z-index']
或 cs.zIndex
。其中,getProperty
方法中的参数,必须是使用中划线的方式表示的属性字符串。
var style = window.getComputedStyle(box);
var marginLeft1 = style.getPropertyValue('margin-left');
var marginLeft2 = style.marginLeft;
此方法不兼容 IE8 及以下
3. currentStyle
IE 中使用的兼容用法
oDiv.currentStyle
4. 封装
4.1 获取元素的样式值
实现一个函数,获取某个元素的样式的样式值
//=> try-catch
function getCss(ele, attr) {
var res = null;
try {
res = window.getComputedStyle(ele)[attr];
} catch (e) {
res = ele.currentStyle[attr];
}
return res;
}
//=> 条件判断
function getCss(ele, attr) {
var res = null;
if(window.getComputedStyle) {
res = window.getComputedStyle(ele)[attr];
} else {
res = ele.currentStyle[attr];
}
return res
}
//=> typeof
typeof window.getComputedStyle != 'undefined'
提高函数的适用率:
把返回的带数字和单位的值,变为数字返回
把不是数字加单位的值,直接返回
function getCss(ele, attr) {
var res = null;
try {
res = window.getComputedStyle(ele)[attr];
} catch (e) {
res = ele.currentStyle[attr];
}
//=> 判断 res 是不是数字加单位的类型
//=> 使用 parseFloat
isNaN(parseFloat(res)) ? null : res = parseFloat(res);
//=> 使用正则
var reg = /[+-]?(\d|[1-9]\d+)(\.\d+)?(px|rem|em|pt)?/;
if(reg.test(res)) {
res = parseFloat(res);
}
return res;
}
4.2 设置元素样式
由于 getComputedStyle
或 currentStyle
是只读的,所以只能通过添加行内样式来改变元素的样式。
function setCss(ele, attr, value) {
//=> 如果必须加单位的没有加单位,手动给它加上默认单位 px
//=> 使用正则
var reg = /width|height|fontSize|/i
ele.style[attr] = value;
}
批量设置
function setGroup(ele, obj) {
if (Object.prototype.toString.call(obj) !== "[object Object]") {
return;
}
for(var k in obj) {
if (obj.hasOwnProperty(k)) {
setCss(ele, k, obj[k]);
}
}
}
4.3 综合方法 css
需求:
css(oDiv, 'width')
:获取css(oDiv, 'heihgt', 300)
:设置css(oDiv, {width: 100, color: '#ccc'})
:批量设置
function css() {
var arg = arguments;
if (arg.length ==2) {
if (typeof arg[1] === 'string') {
return getCss(arg[0], arg[1]);
}
setGroup(arg[0], arg[1])
} else {
setCss(arg[0], arg[1], arg[2])
}
}