利用原生JavaScript获取元素样式只是获取而已_javascript技巧

WBOY
Release: 2016-05-16 16:34:42
Original
1019 people have browsed it

ps:是获取样式,不是设置样式。若没有给元素设置样式值,则返回浏览器给予的默认值。(论坛整理)

1、element.style:只能获取写在元素标签中的style属性里的样式值,无法获取到定义在和通过 加载进来的样式属性

复制代码代码如下:

var ele = document.getElementById('ele');
ele.style.color; //获取颜色

2、window.getComputedStyle():可以获取当前元素所有最终使用的CSS属性值。

复制代码代码如下:

window.getComputedStyle("元素", "伪类");

这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:before”) 。如果不需要伪元素信息,第二个参数可以是null。也可以通过document.defaultView.getComputedStyle(“元素”, “伪类”);来使用

复制代码代码如下:

var ele = document.getElementById('ele');
var styles = window.getComputedStyle(ele,null);
styles.color; //获取颜色

可以通过style.length来查看浏览器默认样式的个数。IE6-8不支持该方法,需要使用后面的方法。对于Firefox和Safari,会把颜色转换成rgb格式。

3、element.currentStyle:IE 专用,返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的

复制代码代码如下:

var ele = document.getElementById('ele');
var styles = ele.currentStyle;
styles.color;

注意:对于综合属性border等,ie返回undefined,其他浏览器有的返回值,有的不返回,但是borderLeftWidth这样的属性是返回值的

4、getPropertyValue():获取CSS样式的直接属性名称

复制代码代码如下:

var ele = document.getElementById('ele');
window.getComputedStyle(ele,null).getPropertyValue('color');

注意:属性名不支持驼峰格式,IE6-8不支持该方法,需要使用下面的方法

5、getAttribute():与getPropertyValue类似,有一点的差异是属性名驼峰格式

复制代码代码如下:

var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("backgroundColor");

注意:该方法只支持IE6-8。

下面的获取样式方法兼容IE、chrome、FireFox等

复制代码代码如下:

function getStyle(ele) {

var style = null;

if(window.getComputedStyle) {

style = window.getComputedStyle(ele, null);

}else{

style = ele.currentStyle;

}
return style;
}

在JQuery中,常用css()获取样式属性,其底层运作就应用了getComputedStyle以及getPropertyValue方法。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!