js获取某元素的class里面的css属性值代码
用js如何获取div中css的margin、padding、height、border等。你可能说可以直接用document.getElementById("id").style.margin获取。但是你说的只能获取直接在标签中写的style的属性,无法获取标签style外的属性(如css文件中的属性)。而下面方法则两者值都可以获取。
实例效果图如下:
Js代码
functiongetStyle(obj,attr){
varie=!+"\v1";//简单判断ie6~8
if(attr=="backgroundPosition"){//IE6~8不兼容backgroundPosition写法,识别backgroundPositionX/Y
if(ie){
returnobj.currentStyle.backgroundPositionX+""+obj.currentStyle.backgroundPositionY;
}
}
if(obj.currentStyle){
returnobj.currentStyle[attr];
}
else{
returndocument.defaultView.getComputedStyle(obj,null)[attr];
}
}
完整实例测试代码:
Html代码
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
<title>js获取某元素的class里面的css属性值</title>
<style>
#box1{margin:5px;padding:5px;height:100px;width:200px;}
a{border:1pxsolid#ccc;border-radius:3px;padding:3px5px;margin:5px0;display:inline-block;background:#eee;color:#f60;text-decoration:none;font-size:12px;}
a:hover{color:#ff0000;background:#fff;}
</style>
</head>
<body>
<divid="box1">box1的css.#box1{margin:5px;padding:5px;height:100px;width:200px;}</div>
<ahref="javascript:;"onclick="getcss("marginTop")">获取box1的margin-top</a><br/>
<ahref="javascript:;"onclick="getcss("paddingTop")">获取box1的padding-top</a><br/>
<ahref="javascript:;"onclick="getcss("height")">获取box1的height</a><br/>
<script>
//获取class里面的属性值
vardivs=document.getElementById("box1");
functiongetStyle(obj,attr){
varie=!+"\v1";//简单判断ie6~8
if(attr=="backgroundPosition"){//IE6~8不兼容backgroundPosition写法,识别backgroundPositionX/Y
if(ie){
returnobj.currentStyle.backgroundPositionX+""+obj.currentStyle.backgroundPositionY;
}
}
if(obj.currentStyle){
returnobj.currentStyle[attr];
}
else{
returndocument.defaultView.getComputedStyle(obj,null)[attr];
}
}
functiongetcss(typ){
alert(getStyle(divs,typ));
}
</script>
</body>
</html>
相关文章
- css opacity属性_CSS中的opacity属性[通俗易懂]
- 初识js中的闭包_Js闭包中变量理解
- 【说站】CSS中in JS是什么意思
- Fabric.js 保存自定义属性
- 前端面试题 --- JS高阶和其他
- 在 Vue.js 中通过计算属性动态设置属性值
- js为一个对象Object添加一个新的属性和值详解编程语言
- JS currentStyle属性和getComputedStyle()方法:读取CSS显示样式
- 使用JS操作Oracle数据库探索潜在可能性(js和oracle数据库)
- JS动态加载脚本的4种方法
- JS图片浏览组件PhotoLook的公开属性方法介绍和进阶实例代码
- 关于js类的定义
- js正则表达式之RegExp对象属性lastIndex,lastMatch,lastParen,lastContext,rightContext属性讲解
- 解决js正则匹配换行问题实现代码
- 让低版本浏览器支持input的placeholder属性(js方法)
- IE8对JS通过属性和数组遍历解析不一样的地方探讨
- PHP加密函数Javascript/Js解密函数
- css样式标签和js语法属性区别
- 判定是否原生方法的JS代码
- JS获取html对象的几种方式介绍
- JS将所有对象s的属性复制给对象r(原生js+jquery)
- js面向对象之静态方法和静态属性实例分析
- js和jquery设置disabled属性为true使按钮失效