day-3.1 操作CSS

一、操作CSS样式

CSS 样式:html文档最终在浏览器中的渲染效果是由CSS决定的,而JS操作HTML文档动态展示,其实就是操作CSS。

javascript操作CSS样式,CSS样式类型:

1、外部样式表:不建议操作

2、内部样式表:优先级不确定

3、行内样式:javascript操作样式的时候最常做的就是操作行内样式,行内样式优先级最高。

操作行内样式的方式

1、通过元素对象的style属性操作html元素标签的行内属性样式。

1 <body>
2     <div id="wrap"></div>    
3     <script>
4         var a = document.getElementById("wrap");
5         a.style = "width:100px;height:100px;background-color:pink;"
6         </script>
7     </body>

不推荐使用,console.dir(a.style);可以发现a.style是一个所有行内CSS样式集合的对象,直接给style这个对象赋值,可能会在某些浏览器调试的时候出现问题;

2、推荐精准选择后修改元素对象的行内CSS样式;

示例:

 1 <body>
 2     <div id="wrap"></div>    
 3     <script>
 4         var a = document.getElementById("wrap");
 5         //a.style = "width:100px;height:100px;background-color:pink;"
 6         a.style.backgroundColor = "pink";
 7         a.style.width = "200px";
 8         a.style.height = "200px";
 9     </script>
10 </body>

 

3、如果多条样式的时候可以通过style这个行内样式属性合集对象的cssText去修改。

示例:

1 <body>
2     <div id="wrap"></div>
3     <script>
4         var a = document.getElementById("wrap");
5         a.style.cssText = "width:100px;height:100px;background-color:green;";
6     </script>
7 </body>

注意:元素对象.style.(css样式)只能获取行内样式的值

举例:

css样式写在style标签内,所有a.style.width获取到的是空字符串

 1 <style>
 2         #wrap {
 3         width:100px;
 4         height:200px;
 5         background-color:pink;
 6                }
 7 </style>
 8 <body>
 9      <div id="wrap"></div>        
10      <script>
11      var a = document.getElementById("wrap");
12          console.log(typeof a.style.width); //string ""
13      </script>
14  </body>

 

 二、特殊行内样式对象属性

有一些属性样式写法特殊,而且各个浏览器兼容性也不同,最常用的是float属性

修改float更多的时候是通过修改类名去实现,比如

<style>
    .fl {
         float :left;
    }
  .fr {
     float:right;
}
</style> <body> <div id="wrap"></div> <script> var a = document.getElementById("wrap"); a.style.width = "200px"; a.className = ".flLeft" </script> </body>

 

 

posted @ 2018-05-18 19:45  bibiguo  阅读(110)  评论(0)    收藏  举报