获取对象在内存中计算后的样式
2015-08-22 15:23
716 查看
获取对象在内存中计算后的样式
下面的例子显示obj.style只能取得”内敛style”的值对于<style></style>中的css属性值,则无能为力
<style type="text/css"> .test1{ background: purple; } .test2{ background: pink; } </style> </head> <body> <div class='test1' onclick="ch()" style="width:300px;height:300px;border-bottom:1px solid red;"> 点击DIV,使其背景色红绿交替 </div> </body> <script type="text/javascript"> function ch(){ var div=document.getElementsByTagName('div')[0]; if(div.className.indexOf("test1")>=0) { div.className="test2"; } else { div.className="test1"; } //var obj=document.getElementsByClassName('test1'); // var a=obj.style.width; // var b=obj.style.height; // var c=obj.style.borderBottomWidth; div.style.width=parseInt(div.style.width)+5+'px'; div.style.height=parseInt(div.style.height)+5+'px'; div.style.borderBottomWidth=parseInt(div.style.borderBottomWidth)+10+'px'; } </script>
我们可以用obj.currentStyle (ie内核) 和window.getComputedStyle(一般浏览器内核)来获取.
注意:只有IE和Opera支持使用currentStyle获取HTMLElement的计算后的样式,其他浏览器中不支持
标准浏览器中使用getComputedStyle,IE9以上也支持getComputedStyle.
window.getComputedStyle(obj,伪元素)
参数说明
第一个参数为要获取计算后的样式的目标元素
第二个参数为期望的伪元素,如:’after’,’frist-letter’等,一般为null
考虑兼容性,封装函数
function getStyle:function(el,attr){
returnel.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];
}
注意:这2个方法,获取的对象是只读的,要改样式,还得靠obj.style
eg:
<style type="text/css"> div { width: 300px; height: 300px; border-bottom: 1px solid red; } .test1{ background: purple; } .test2{ background: pink; } </style> </head> <body> <div class='test1' onclick="ch()" > 点击DIV,使其背景色红绿交替 </div> </body> <script type="text/javascript"> function getStyle(el,attr){ return el.currentStyle ? el.currentStyle[attr]:getComputedStyle(el,null)[attr]; } function ch(){ var div=document.getElementsByTagName('div')[0]; if(div.className.indexOf("test1")>=0) { div.className="test2"; } else { div.className="test1"; } //alert(getStyle(div ,'width')); //return; div.style.width=parseInt(getStyle(div ,'width'))+5+'px'; div.style.height=parseInt(getStyle(div ,'height'))+5+'px'; div.style.borderBottomWidth=parseInt(getStyle(div ,'borderBottomWidth'))+10+'px'; } </script>
相关文章推荐
- CSS的table的实现,实现表格的单行边框显示,换行显示效果
- CSS+JS 悬浮固定菜单效果
- CSS经典布局之圣杯布局、双飞翼布局
- Extjs单元格的样式设计
- CSS3入门之文本与字体
- CSS中的margin与padding属性
- css实现手风琴图片特效
- 修改LibreOffice Draw中定义的样式名称
- table表格css样式
- CSS优先级
- [HTML] CSS 下拉列表菜单
- WEB基础之:CSS
- Qt鼠标事件 我的鼠标样式
- css3背景颜色渐变
- NumberPicker 样式设置
- CSS中行高line-height属性的一些使用技巧
- CSS学习笔记之定位
- css position
- css3 transform transition 实现照片墙效果
- CSS3:绘制图形