当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javaScript 读取和设置文档元素的样式属性

Javascript
JavaScript窗口功能指南之检查一个窗口是否存在
用JAVASCIRPT写的一个动态显示日期的函数!
JavaScript窗口功能指南之打开一个新窗口
JavaScript窗口功能指南之在窗口中书写内容
JavaScript窗口功能指南之引用已打开的窗口
JavaScript窗口功能指南之发挥窗口特征
JavaScript窗口功能指南之命名窗口和框架
JavaScript窗口功能指南之创建对话框
对连串英文自动换行的解决方法 IE5.5 无忧脚本
javascript扫雷游戏,版本二
window.external的使用
JavaScript 是什麽?
SelectBox in Frame
24点终结者(javascript)
用Javascript转换源代码
JS特效之状态栏冒泡
JavaScript:实现滚动带链接的字幕
jscript错误代码及相应解释大全
实现随鼠标飘浮移动文字的JavaScript
怎样捕捉 Delete 键

Javascript 中的 javaScript 读取和设置文档元素的样式属性


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 240 ::
收藏到网摘: n/a

有时候我们需要用js设置文档的样式属性,下面就是一些方法与原理分析,大家可以看下,应该就没问题了。 首先我们先说一下样式表属性
1. 内联样式即元素style属性里面设置的,级别最高
2. 页面样式表定义即页面<style></style>里面定义的,级别次之
3.外部链接样式表文件
JavaScript获取和设置文档元素的css属性:
1.获取元素Style属性里面设置的样式属性,
document.getElementById(id).style.height;
有,则返回属性值;没有则返回空
IE和火狐皆然,只是有的属性值返回可能不一样,比如像颜色火狐返回rgb,而IE是返回十六进制数字
测试代码:
<script type="text/javascript">
function getCss(){
alert(document.getElementById("aaa").style.height);
alert(document.getElementById("aaa").style.backgroundColor);
alert(document.getElementById("aaa").style.width);
document.getElementById("aaa").style.backgroundColor = ‘#dbdbdb';
//alert(myWidth);
}
</script>
<div id="aaa" class="bbb" style="height:20px; background-color:#FF0000;">
asdfasdfas
</div>
<input type="button" value="点击" onclick="getCss();" />
2.有时候我们的样式可能有多个地方设置了,我们也不知道它到底是外部样式表属性起作品,还是在内联样式里面起作用,所以我们就需要获取当前页面渲染的属性值。这个在IE和FF里面有些不同:
示例代码片断:
IE:document.getElementById('aaa').currentStyle.height
FF标准:document.defaultView.getComputedStyle(aaa,null).getPropertyValue('height')
这两个属性是只读的,若要改变元素样式还得使用style,它直接写在元素style属性里面级别最高起作用
3.写一个兼容IE和FF的函数来调用
复制代码 代码如下:

function getRealStyle(id,styleName) {
var element = document.getElementById(id);
var realStyle = null;
if (element.currentStyle)
realStyle = element.currentStyle[styleName];
else if (window.getComputedStyle)
realStyle = window.getComputedStyle(element,null)[styleName];
return realStyle;
}

调用:cur_height = parseInt(getRealStyle(CON_ID,'height'));
P.S:返回值通常会带有单位,需要使用parseInt函数提取数字,以方便后面的操作