Heim  >  Artikel  >  Web-Frontend  >  js正确获取元素样式详解_javascript技巧

js正确获取元素样式详解_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:48:361198Durchsuche

在说js获取元素样式之前,简单地谈一下样式

样式分三种
外部样式 External Style Sheet
以CSS为扩展名的文件(又称为"超文本样式表"文件),它的作用范围可以是多张网页,或整个网站,甚至不同的网站。与网页链接后,才能应用。
嵌入式样式 internal Style Sheet
包含在网页内部的样式设置,它的作用范围仅限于嵌入的网页。
内联式样式 inline Style
在HTML文档中,内联式样式表的格式化信息直接插入所应用的网页元素的HTML标签中,作为其HTML标签的属性参数。严格地说,内联样式表称不上表,仅仅是一条HTML标记。
当出现相同的样式时,优先级是内联大于嵌入式样式, 嵌入式样式大于外部样式。
---------------------------------------------------------------
当js获取这三种样式时,style只能获取内联样式,获取不到外部样式和嵌入式样式,因此要用currentStyle属性,而currentStyle在FF下不支持
下面介绍二种 兼容FF和IE和正确获取样式的方法

复制代码 代码如下:

var $=function(id){return document.getElementById(id) };
方法一
/*
* @string id
* @string styleName 样式名
*/
function getEyeJsStyle(id,styleName){
if($(id).currentStyle){//ie
return $(id).currentStyle[styleName];
}else{ //ff
var $arr=$(id).ownerDocument.defaultView.getComputedStyle($(id), null);
return $arr[styleName];
}
}

方法二:
复制代码 代码如下:

HTMLElement.prototype.__defineGetter__("currentStyle", function () {
return this.ownerDocument.defaultView.getComputedStyle(this, null);
});

讲述一下getComputedStyle函数的用法
这个函数有两个参数:
第一个参数为需要获取样式的元素对象;
第二个参数为伪元素,如:hover, :first-letter, :before等等,
如果不需要伪元素则该参数为null。
getComputedStyle()函数可以从 document.defaultView 对象中访问到,即可以这样调用该函数
--------------------------------------------------------------------------------------------

顺便说一下runtimeStyle属性,首页该属性只在IE中支持,在FF不支持
runtimeStyle 运行时的样式!如果与style的属性重叠,将覆盖style的属性!
意思就是当指定了runtimeStyle,那么当前显示的样式以runtimeStyle为准,如果取消了runtimeStyle,那么当前显示样式就恢复到currentStyle的样式。
案例:
设置document.getElementById("eyejs").runtimeStyle.width="400px"; 那该元素的宽度就是400px,,将覆盖style的属性
案例分析打包下载
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn