随笔 - 143  文章 - 0  评论 - 23  阅读 - 125万

js(1)取样式表中的样式

首先我们先说一下样式表属性
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函数提取数字,以方便后面的操作

posted on   cbwcwy  阅读(2662)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2012年11月 >
28 29 30 31 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示