码迷,mamicode.com
首页 > 其他好文 > 详细

style、currentStyle、getComputeStylel的使用

时间:2014-09-10 10:45:20      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   java   ar   div   cti   

(1)js中使用obj.style的用法,是为了获得内联样式,即style属性中的值。

如果想获取obj.style.display,但内联样式表中没有定义display,那么将返回一个空的字符串。

(2)使用obj.currentStyle则是为了获得外部(即通过<link>引入)和内部(即<style>中定义)的样式表中的值。

currentStyle 对象反映了样式表中的样式优先顺序。在 HTML 中此顺序为:内嵌样式、样式表规则、HTML 标签属性、HTML 标签的内部定义。

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <style type="text/css">
 7             #text{
 8                 width: 200px;
 9                 height: 30px;
10             }
11         </style> 
12         <script type="text/javascript">
13             function objClick(obj){
14                 alert(obj.style.width);
15                 alert(obj.currentStyle.height);
16             }
17         </script>
18     </head>
19     <body>
20         <div>
21             <input type="button" id="text" value="click" style="border:1px solid #f00" onclick="objClick(this)">
22         </div>
23     </body>
24 </html>

注意:只有 IE 和 Opera 支持使用 currentStyle 获取 HTMLElement 的计算后的样式,其他浏览器中不支持。ps:由于忽略了这个条件,一直在chrome下调试,怎么都不起作用,所以浏览器的兼容性,一定要切记。

(3)window.getComputedStyle(obj,null)
Dom中getComputedStyle方法可用来获取元素中所有可用的css属性列表,以数组形式返回,并且是readonly的。
参数说明:
第一个参数为要获取计算后的样式的目标元素
第二个参数为期望的伪元素,如 ‘:after‘,‘:first-letter‘ 等,而不是伪类如 ‘:hover‘ 等。
注意:在 Firefox 中,第二个参数是必须的,如果没有期望的伪元素要设置为 ‘null‘,这与规范的要求相符。在 Chrome Safari Opera 中,第二个参数如果为 ‘null‘ 则可以省略。
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <style type="text/css">
 7             #text{
 8                 width: 200px;
 9                 height: 30px;
10             }
11         </style> 
12         <script type="text/javascript">
13             function objClick(obj){
14                           alert(window.getComputedStyle(obj,null).getPropertyValue("width"));
15                           alert(window.getComputedStyle(obj,null).getPropertyCSSValue("width").cssText);
16                }
17         </script>
18     </head>
19     <body>
20         <div>
21             <input type="button" id="text" value="click" style="border:1px solid #f00" onclick="objClick(this)">
22         </div>
23     </body>
24 </html>

 经测试:第一种方法,在IE和chrome中通用,第二种,IE下不支持。

 

style、currentStyle、getComputeStylel的使用

标签:style   blog   color   io   使用   java   ar   div   cti   

原文地址:http://www.cnblogs.com/lonelybonze/p/3963938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!