Javascript改变和获取样式详解

来源:互联网 发布:jrtplib java 编辑:程序博客网 时间:2024/05/21 22:59

HTML

<div id="box" class=""></div>

1.利用Javascript来改变网页中div的CSS样式

//行内式
var div=document.getElementById("box");
div.style.width="300px";
div.style.height="300px";
div.style.backgroundColor="red";
div.style.margin="0 auto";

//嵌入式,配合类名来改变样式,需要定义一个CSS的样式类,通过JS来得到类名

/*css样式类*/
.cssStyle{
        width: 300px;
height: 300px;
background-color: red;
margin: 0 auto;
}

       div.className="cssStyle";

//通过cssText属性来批量设置样式,这也是个行内式
       div.style.cssText="width: 300px;height: 300px;background-color: red;margin: 0 auto;";

//cssText的使用会清除之前元素含有的样式,所以你想保留之前的样式并且设置新的样式,得使用
       div.style.cssText+="width: 300px;height: 300px;background-color: red;margin: 0 auto;";

//但是在IE中的最后一个分号会被删除
       div.style.cssText+="width: 300px;height: 300px;background-color: red;margin: 0 auto;";//这样便能解决在IE中出现的问题了

 //为了让代码更美观和调用灵活性更高,封装一个简单的方法
      function setStyle(obj,value){
    for(var i in value){
          obj.style[i]=value[i];
}
}

setStyle(div,{width:"300px",height:"300px",backgroundColor:"red",margin:"0 auto"});//调用函数设置样式

1.利用Javascript来获取网页中div的CSS样式

//行内式,输出div宽度真实大小,只能获取行内式的CSS属性
                console.log(div.style.width);

//既能获取行内式,也能获取嵌入式,返回一个数值,但是这个数值等于宽度加上border边框值(如有)的大小
                console.log(div.offsetWidth);

//函数名方法既能获取行内式,也能获取嵌入式,输出div宽度真实大小,但不支持IE浏览器
               console.log(getComputedStyle(div,false).width);
//IE浏览器的函数解决方法,功能与getComputedStyle相仿
               console.log(div.currentStyle.width);

//为了更好的兼容各种浏览器,我们封装一个简单获取样式的函数方法
      function getStyle(obj,name){
     if(obj.currentStyle){
  return obj.currentStyle[name];
             }else{
          return getComputedStyle(obj,false)[name];
}
}

console.log(getStyle(div,"width"));//调用函数获取输出样式

0 0
原创粉丝点击