您的位置:首页 > Web前端 > CSS

JS操作CSS样式,获取与设置

2013-08-01 23:10 393 查看
HTML页面引入样式,有三种方式:

1、外部样式(external stylesheet):如果很多网页需要用到同样的样式(Styles),将样式(Styles)写在一个以.css为后缀的CSS文件里,然后在每个需要用到这些样式(Styles)的网页里引用这个CSS文件。

2、内部样式(internal stylesheet):是写在HTML的<head></head>里面的,内部样式只对所在的网页有效。

3、内嵌样式(inline style):是写在Tag里面的,内嵌样式只对所有的Tag有效。

当然三种样式的优先级也不是不同的,一般来说,(外部样式)External style sheet <(内部样式)Internal stylesheet <(内联样式)Inlinestyle,当然这样的条件是引进的外部样式位置是位于内部样式之前的。

获取样式:

获取元素的样式属性值:

在IE下,有style、currentStyle、runtimeStyle三种,style只能获取内联样式,currentStyle获取最终样式,runtimeStyle是位于三种样式之上的样式,设置了只能用currentStyle和runtimeStyle访问到,相当于是设置了tag的内联样式,但是style访问不到,最好对于一个DOM元素设置了,也用runtimeStyle访问。具体内容戳这里

在W3C下,也能用style访问内联样式,最终样式document.defaultView.getComputedStyle(elem, null).getPropertyValue(name)访问到。

下面列出总结的获取样式注意的问题:

1.float属性,在IE下要通过styleFloat才能访问到,关于cssFloat,说是标准写法,可是我测试未在FF下不起作用,返回为空值。

2.opacity属性,IE下filter:alpha(opacity=10);标准为opacity:0.1;

3.font-size等中间有横杠之类的属性,IE下要变成驼峰类的形式,FF不用(暂时测试)。

4.当width或者height的值为百分数,或者有"auto"时,需要手动计算值。

下面写出自己的暂时未发现兼容性的获取样式方法,如果发现再补充。

//首字母大写 width返回Width
function capitalize (args){
return args.charAt(0).toUpperCase()+args.substr(1).toLowerCase();
}
//判断数组是否包含该元素
function filters(arr,value){
return arr.toString().indexOf(value)>=0;
}
//margin-top变为marginTop
function camelize(param){
return param.replace(/-(\w)/,function($1,$2){
return $2.toUpperCase();
});
}
function getCss(elem,styles){
var value;
//处理float
if(styles=='float'){
styles=document.defaultView && document.defaultView.getComputedStyle?styles:'styleFloat';
}
if(document.defaultView && document.defaultView.getComputedStyle){
value=document.defaultView.getComputedStyle(elem, null).getPropertyValue(styles);
}else{
styles=camelize(styles);
value=(styles=='opacity')?/opacity=([^)]*)/.test(elem.currentStyle["filter"])?(parseFloat(RegExp.$1)*0.01):1:elem.currentStyle[styles];
}
//处理"auto"跟百分数
if((value=="auto"||value.toString().indexOf("%")>=0)&&filters(["width","height"],styles)){
value=elem["offset"+capitalize(styles)]+"px";
}
return value;
}

关于clss的获取放到后面与设置一起讨论。

设置样式:

设置样式同样包括设置三种样式,外部、内部与内联。

内联样式:

通过elem.style.border="1px solid red"或者

function addLink(url){
var doc=document;
var link=doc.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", url);

var heads = doc.getElementsByTagName("head");
if(heads.length)
heads[0].appendChild(link);
else
doc.documentElement.appendChild(link);
}


样式名称的操作

四个方法,获取,判断,添加,移除

function getClass(elem){
return elem.className.replace(/^\s\s*|\s\s*$/g,'').replace(/\s+/," ").split(" ");
}
function hasClass(elem,name){
return new RegExp('(\\s|^)'+name+'(\\s|$)').test(elem.className); //\在引号内,要多加一个\转义一次
}
function addClass(elem,name){
if(!hasClass(elem,name))
elem.className+=" "+name;
}
function removeClass(elem,name){
if(hasClass(elem,name)){
elem.className=elem.className.replace(new RegExp('(\\s|^)'+name+'(\\s|$)')," ");
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: