知道一个div的宽高背景色,如何不通过写在行间样式的办法更改样式?currentStyle(只兼容ie),getComeputedStyle(兼容)-->获取非行间样式
2015-06-08 18:19
585 查看
知道一个div的宽高背景色,如何不通过写在行间样式的办法更改样式?currentStyle(只兼容ie),getComeputedStyle(兼容ie9以上)-->获取非行间样式
(1)currentStyle 仅支持ie
(2)getComputedStyle,有两个参数,第二个参数可以为任何数,不起实质性作用。
兼容所有浏览器的写法
但是,在实际应用过程中,这样的写法有些复杂,通过封装一个函数来写,将来用的时候再调用。
(1)currentStyle 仅支持ie
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>返回值</title> </head> <style type="text/css"> #div1{width: 200px;height: 200px;background: red;} </style> <script type="text/javascript"> window.onload=function(){ var oDiv=document.getElementById('div1'); alert(currentStyle.width); } </script> <body> <div id="div1"></div> </body> </html>
(2)getComputedStyle,有两个参数,第二个参数可以为任何数,不起实质性作用。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>返回值</title> </head> <style type="text/css"> #div1{width: 200px;height: 200px;background: red;} </style> <script type="text/javascript"> window.onload=function(){ var oDiv=document.getElementById('div1'); alert(getComputedStyle(oDiv,false).width); } </script> <body> <div id="div1"></div> </body> </html>
兼容所有浏览器的写法
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>返回值</title> </head> <style type="text/css"> #div1{width: 200px;height: 200px;background: red;} </style> <script type="text/javascript"> window.onload=function(){ var oDiv=document.getElementById('div1'); if(oDiv.currentStyle){ //ie alert(oDiv.currentStyle.width); } else{ //ff alert(getComputedStyle(oDiv,false).width) } } </script> <body> <div id="div1"></div> </body> </html>
但是,在实际应用过程中,这样的写法有些复杂,通过封装一个函数来写,将来用的时候再调用。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>返回值</title> </head> <style type="text/css"> #div1{width: 200px;height: 200px;background: red;} </style> <script type="text/javascript"> function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; } else{ return getComputedStyle(obj,false)[name]; } } window.onload=function(){ var oDiv=document.getElementById('div1'); alert(getStyle(oDiv,'width')); } </script> <body> <div id="div1"></div> </body> </html>
相关文章推荐
- CSS postion 相对定位、绝对定位、固定定位
- CSS关于绝对位置与相对位置的理解
- CSS中position详解与常见应用实现
- 举例详解CSS中的cursor属性
- css布局样式属性【text-overflow】
- CSS设计之页面滚动条出现时防止页面跳动的方法
- 使用CSS时间打点的Loading效果的教程
- css div position to parent
- 通过position属性实现文本在页面中的任意位置
- 使用CSS代码的空格实现中文对齐的方法
- 深入理解CSS的height:100%和height:inherit之间的使用区别
- CSS3 @font-face
- css3 shadow实现的各种漂亮阴影效果
- css3大小单位px、pt、em和rem的区别
- CSS实现垂直居中的5种方法
- 让IE6支持css3,让 IE7、IE8 都支持CSS3
- css定位
- CSS3 icon font
- css sprite、background-size、Retina屏幕详解
- html/css编写规范