JS中设置元素样式

在JS中,操作元素样式有多种方法,比如:改变元素的style属性,改变样式表(cssRule),改变元素style的cssText属性。但是每次写起来都比较的麻烦,如果要设置高和宽的话,JS里常见的写法是这样:

obj.style.width = 100;
obj.style.height = 100;

如果我们能够像jQuery里那样设置就方便多了,比如像这样:

css(obj,{
	"width":"100px",
	"height":"100px"
});

OK,按照这个思路开写。

css函数的两个功能

首先,css函数要接收两个参数:

  1. obj:要设置样式的Dom对象
  2. arg:字符串或对象

arg参数是字符串的时候,是获取元素的单个属性值,比如:css(obj,"width");是获取objwidth。arg参数是对象的时候,比如:css(obj,{"width":"100px","height":"100px"});是批量设置obj的宽和高为100px

获取元素的样式

获取元素前,我们先需要准备两个函数:一个是获取元素当前样式的函数,一个是将类似于”padding-left”这样的字符串转换成:”paddingLeft”的函数(亲测ie6和火狐不支持”padding-left”这样的写法,所以需要转换)。

获取计算后的样式getStyle函数:

function getStyle(ele,attr){
	if(attr == "width"){
		return ele.offsetWidth;
	}else if(attr == "height"){
		return ele.offsetHeight;
	}
	if(typeof window.getComputedStyle != 'undefined'){
		return window.getComputedStyle(ele,null)[attr];
	}else if(typeof ele.currentStyle != 'undefined'){
		return ele.currentStyle.getAttribute(attr);
	}
}

转换CSS属性格式的cssFormat函数:

function cssFormat(property){
	var str = property.split("-"),
		temp = [];
	for(var i=1;i<str.length;i++){
		temp.push(str[i].charAt(0).toUpperCase()+str[i].substring(1));
	}
	return str[0]+temp.join("");
}

在css函数里,判断如果arg参数为一个字符串,则返回获取到的样式值:

function css(obj,arg){
	if('string'== typeof arg){
		$css = cssFormat(arg);
		return parseInt(getStyle(obj,$css)) + "px";
	}

设置元素的样式

如果传过来的arg是一个对象的话,则需要遍历这个对象里的键值,每遍历到一个,就把元素stylecssText改变一下即可(由于低版本的IE浏览器不支持opacity属性,所以透明度属性需要添加一个IE的滤镜来实现):

var $cssText = "";
for(var j in arg){
	$cssText += j + ":" + arg[j] + ";";
	if("opacity" == j){
		$cssText += "filter:alpha(opacity="+(parseFloat(arg[j])*100)+");";
	}
	obj.style.cssText = $cssText;
}

完整代码

function css(obj,arg){
	if('string'== typeof arg){
		$css = cssFormat(arg);
		return parseInt(getStyle(obj,$css)) + "px";
	}
	var $cssText = "";
	for(var j in arg){
		$cssText += j + ":" + arg[j] + ";";
		if("opacity" == j){
			$cssText += "filter:alpha(opacity="+(parseFloat(arg[j])*100)+");";
		}
		obj.style.cssText = $cssText;
	}
	function getStyle(ele,attr){
		if(attr == "width"){
			return ele.offsetWidth;
		}else if(attr == "height"){
			return ele.offsetHeight;
		}
		if(typeof window.getComputedStyle != 'undefined'){
			return window.getComputedStyle(ele,null)[attr];
		}else if(typeof ele.currentStyle != 'undefined'){
			return ele.currentStyle.getAttribute(attr);
		}
	}
	function cssFormat(property){
		var str = property.split("-"),
			temp = [];
		for(var i=1;i<str.length;i++){
			temp.push(str[i].replace(/^[a-zA-Z]/,str[i].charAt(0).toUpperCase()));
		}
		return str[0]+temp.join("");
	}
}

OK,现在就可以很轻松的获取和设置元素的样式啦,比如:

获取元素的宽度:

css(obj,"width");

设置元素的宽、高、透明度:

css(obj,{
	"width":"100px",
	"height":"100px",
	"opacity":"0.5"
});