获取css样式,style、getComputedStyle及currentStyle的区别
2024-08-27 22:22:01
样式表有三种:
内嵌样式:<div id="box" style="color:red">box</div>,style写在html中的为内嵌样式;
内联样式:
<style>
#box{
font-size: 25px;
background-color: #ccc;
}
</style>
在html页中直接写入<style></style>的为内联样式;
外部样式:<link rel="stylesheet" href="css/style.css" />这种为外部样式。
现在来测试一个小例子:
<style>
#box{
font-size: 25px;
background-color: #ccc;
}
</style>
<div id="box" style="color:red">box</div>
js代码:
window.onload=function(){
var box=document.getElementById('box');
alert(box.style.color); //弹出red element.style[attr]对内嵌样式有效
alert(box.style.fontSize); //弹出空 从这里可以看出element.style[attr]只对内联样式无效
alert(isStyle(box,'color')); //使用isStyle方法,弹出rgb(255,0,0)
alert(isStyle(box,'fontSize')); //使用isStyle方法,弹出25px
} /*通过元素节点和属性获取属性值*/
function isStyle(ele,attr){
if(window.getComputedStyle!='undefined'){ //兼容firefox
return window.getComputedStyle(ele,null)[attr];
}else if(ele.currentStyle!='undefined'){ //兼容IE
return ele.currentStyle[attr];
}
}
要想获取内部样式以及外部样式需要通过getComputedStyle和currentStyle来获取,当然也可以获取内嵌样式。
最新文章
- Unity Android加密DLL笔记
- 关于echarts3地图下钻省市
- Linux EOF使用
- ytu 1910:字符统计(水题)
- java 动态代码生成。
- Leetcode#139	Word Break
- asp.net Calendar 日历控件用法
- c++ read
- 为什么样本方差(sample variance)的分母是 n-1?
- hadoop笔记之MapReduce的应用案例(WordCount单词计数)
- IT忍者神龟之使用 PowerDesigner
- Python基础学习总结(持续更新)
- pycharm的console显示乱码和中文的配置
- Hadoop经典案例(排序&;Join&;topk&;小文件合并)
- [原][spark]帧序列的纹理UV索引,修改spark源码,改变纹理索引方式,支持常规帧序列
- 网站如何实现 在qq中发自己链接时,便自动获取链接标题、图片和部分内容
- Codeforces Round #352 (Div. 2) B. Different is Good 水题
- 后缀树 &; 后缀数组
- js中一次性注册多个事件
- pandas安装及使用