JS获取CSS样式的问题
2016-03-11 21:52
435 查看
今晚做一个小小的JS效果时,突然发现用JS获取CSS样式时只能获取到内部的,也就是写在HTML标签里的style,如果把样式写在<head></head>或者是CSS文件里面就获取不了,用alert()调试一下,就只弹出一个,什么也没有。于是就去网上找了下资料,果然,让我找到解决的办法。解决办法如下:
如果浏览器是IE内核的话用object.currentStyle就行了,即
对象.currentStyle.属性名
如果是FireFox的话就用document.defaultView.getComputedStyle(obj,null)这个比较复杂一点,在下也不是很懂.
当然我们一般都是将这两种结合起来,然后判断是什么浏览器来决定用哪个
网上一些代码是这样的
<script type=”text/javascript”>
function GetCurrentStyle (obj, prop) {
if (obj.currentStyle) {
return obj.currentStyle[prop];
}
else if (window.getComputedStyle) {
prop = prop.replace (/([A-Z])/g, “-$1”);
prop = prop.toLowerCase ();
return document.defaultView.getComputedStyle (obj,null)[prop];
}
return null;
}
var dd=document.getElementById(“qq”);
alert(GetCurrentStyle(dd,”width”));
</script>
然而我却屡试都错,我就慢慢调试,得到自己的版本
function getStyle(obj){
if(obj.currentStyle){
return obj.currentStyle
}
else if(window.getComputedStyle)
return document.defaultView.getComputedStyle(obj,null)
return null;
}
简单了很多,直接不传属性值进来,因为在调试哪里出错的时候,发现正是属性值那有问题,虽然getComputedStyle是以数组的形式返回的,但我发现用网上的代码那样直接获取属性值的时候返回来的居然是undefined,于是就删掉属性值,然后这样写getStyle(obj).属性名 获取属性的值就成功了。
这是我这个渣渣第一次注册CSDN博客,也是第一次发博客,纯属纪念一下我在写代码的时候遇到的问题,以后忘记了好查看。
如果浏览器是IE内核的话用object.currentStyle就行了,即
对象.currentStyle.属性名
如果是FireFox的话就用document.defaultView.getComputedStyle(obj,null)这个比较复杂一点,在下也不是很懂.
当然我们一般都是将这两种结合起来,然后判断是什么浏览器来决定用哪个
网上一些代码是这样的
<script type=”text/javascript”>
function GetCurrentStyle (obj, prop) {
if (obj.currentStyle) {
return obj.currentStyle[prop];
}
else if (window.getComputedStyle) {
prop = prop.replace (/([A-Z])/g, “-$1”);
prop = prop.toLowerCase ();
return document.defaultView.getComputedStyle (obj,null)[prop];
}
return null;
}
var dd=document.getElementById(“qq”);
alert(GetCurrentStyle(dd,”width”));
</script>
然而我却屡试都错,我就慢慢调试,得到自己的版本
function getStyle(obj){
if(obj.currentStyle){
return obj.currentStyle
}
else if(window.getComputedStyle)
return document.defaultView.getComputedStyle(obj,null)
return null;
}
简单了很多,直接不传属性值进来,因为在调试哪里出错的时候,发现正是属性值那有问题,虽然getComputedStyle是以数组的形式返回的,但我发现用网上的代码那样直接获取属性值的时候返回来的居然是undefined,于是就删掉属性值,然后这样写getStyle(obj).属性名 获取属性的值就成功了。
这是我这个渣渣第一次注册CSDN博客,也是第一次发博客,纯属纪念一下我在写代码的时候遇到的问题,以后忘记了好查看。
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 最后一次说说闭包
- Ajax
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子
- JavaScript 各种遍历方式详解
- call/apply/bind 的理解与实例分享