js原生获取css属性

原文参考http://blog.csdn.net/lzding/article/details/46317777

1.写在dom上的属性,内联样式
<div id="box" style="background-color:#ccc;margin-top:100px;"></div>
var oBox = document.getElementById(‘box‘)
console.log(oBox.style.width)

1)对于复合属性(如background),假设行间设置了样式:background-color:#333,不能通过 element.style.background 来获取(见上面例子)
2)css属性使用驼峰法,如 backgroundColor、marginTop等。

2.写在css中的属性,非内联样式(chrome)
var oBox = document.getElementById(‘box‘);
var a = getComputedStyle(oBox, null)[‘width‘]; // 100px

1)对于复合属性:使用 getPropertyValue 获取属性值时,不能使用驼峰写法,如:例子中的 getpropertyValue(‘backgroundColor‘) 无法正确获得值,而必须写成 background-color
2)另外,以下写法也正确:getComputedStyle(oBox, null)[‘backgroundColor‘]、getComputedStyle(oBox, null)[‘background-color‘], 以及 getComputedStyle(oBox, null).backgroundColor 等

时间: 2024-08-11 07:49:29

js原生获取css属性的相关文章

js中获取css属性

直接获取 window.onload = function() { var but = document.getElementById('button'); var div = document.getElementById('getStyle'); but.onclick = function() { alert(div.style.width);//弹出空的对话框 } } getComputedStyle(div)方法 用法 window.onload = function() { var

JS获取CSS属性值

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <ti

js中获取css样式属性值

关于js中style,currentStyle和getComputedStyle几个注意的地方 (1)用js的style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的. (2)currentStyle可以弥补style的不足(可获取内联样式,内部样式和外部样式),但是只适用于IE. (3)getComputedStyle同currentStyle作用相同,但是适用于FF.opera.safari.chrome. 注意: ① currentStyle和getComputedS

js如何获取给定属性的属性值

js如何获取给定属性的属性值:在一些实际应用中需要取得给定属性的属性值,下面就简单介绍一下如何实现次效果.代码实例如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.51texiao.cn/" /> <title>蚂蚁部落</ti

js原生获取className&amp;多选一

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js原生获取class名&多取一</title> </head> <body> <ul> <li class="red blue green">111</li> <

JS使用getComputedStyle()方法获取CSS属性值

在对网页进行调试的过程中,经常会用到js来获取元素的CSS样式,方法有很多很多,现在仅把我经常用的方法总结如下: 1. obj.style:这个方法只能JS只能获取写在html标签中的写在style属性中的值(style="-"),而无法获取定义在<style type="text/css">里面的属性. 2. IE中使用的是obj.currentStyle方法,而FF是用的是getComputedStyle 方法 "DOM2级样式"

JS里引用CSS属性时候的命名

????如果JS代码中设置<p>元素的另一个CSS属性font-family.这个属性的获取方式与color属性略有不同,因为 font和family之间的连字符与JS中减法操作符相同,JS会把它解释为减号.如果你像下边这样访问名为 font-family 的属性,会收到一条出错信息: ????Element.style.font-family ????JS将减号前边的内容解释为"元素的style属性的font属性",把减号后的内容解释为一个名为family的变量,将整个表

jquery学习 - jquery选择孩子元素和个数/获取css属性

选择器 选择孩子元素和css属性 获得孩子元素的个数 选择器 jquery的选择器很强大,可以的话,能用jquery的时候,真的是非常方便. 选择孩子元素和css属性 先看下面的代码: SelectColor = $(ColorId).children('svg').children('rect').css('fill'); 这个代码很容易懂.首先: ColorId = $("#id"); svg是一个子元素的标签. rect是svg下的子元素 fill是rect的一个css属性 可以

JS 获取CSS属性值

obj: 元素对象 attribute: 属性 返回值:该对象这个属性的值 function getDefaultStyle(obj,attribute){ // 返回最终样式函数,兼容IE和DOM,设置参数:元素对象.样式特性 return obj.currentStyle?obj.currentStyle[attribute]:document.defaultView.getComputedStyle(obj,false)[attribute]; } 完整链接:http://www.css8