获取对象在内存中计算后的样式
来源:互联网 发布:开网店软件 编辑:程序博客网 时间:2024/05/26 12:56
获取对象在内存中计算后的样式
下面的例子显示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>
0 0
- 获取对象在内存中计算后的样式
- 计算Java对象在内存中占用空间
- 对象在内存中结构
- Image在内存中占用的空间计算
- Image在内存中占用的空间计算
- 创建对象在内存中,程序的执行过程
- java 对象创建时,在内存中加载的过程
- 运行时java对象在内存中是什么样子的?
- java对象在内存中存储的布局
- 获取计算后的css样式
- JavaScript 获取计算后的样式
- 74 Java 对象在内存中状态
- 函数、对象在内存中存在形式
- FiveDay(浅谈对象在内存中)
- 在内存剖析对象
- 在内存剖析对象
- 学习心得——数组作为函数参数后sizeof获取不到数组在内存中所占字节数的问题
- 学习心得——数组作为函数参数后sizeof获取不到数组在内存中所占字节数的问题
- 加速Android Studio/Gradle构建
- 周赛4
- Xcode工程中的Project和Target区别
- iOS开发:FMDB的使用
- 高斯过程(Gaussian Process)
- 获取对象在内存中计算后的样式
- UVA101-The Blocks Problem
- 正则表达式-数字每隔3位加入逗号
- 快学Scala习题解答—第十章 特质
- C++内存地址分配和内存区划分简介
- SharedPreferences 存储
- CODE COMPLETE 2e Chapter 6
- I - 么
- 华为OJ(表达式求值)