博客
关于我
js中style,currentStyle和ge…
阅读量:161 次
发布时间:2019-02-28

本文共 834 字,大约阅读时间需要 2 分钟。

原文地址:
作者:
周末写了个原生的animation组件,其中使用原生的document.getElementByIdx_x_x('...').style来获取元素的相关样式值,但是奇怪的是获取不到相应的值:
<style>
body{margin:0 auto;text-align:center;}
div{position:relative;left:10px;}
</style>
<div id="pic1">
<img src="http://pic1.xihuan.me/edr/196__/t02362982432fa1b14e.jpg">
</div>
<script>
var dom1 = document.getElementByIdx_x('pic1');
console.log(dom1.style.left);
</script>
控制台中显示为空。 
查询了相关资料发现问题如下:
style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。
currentStyle可以弥补style的不足,但是
只适用于IE
getComputedStyle同currentStyle作用相同,但是
适用于FF、opera、safari、chrome
写了个getStyle的自定义函数,来兼容ie和其他浏览器,使用getStyle来获取页面中元素的样式,问题解决。
getElementStyle: function(el,attr){
//获取el当前的attr样式,解决ie问题
return el.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];
}
获取后返回10px。
注意:
currentStyle和getComputedStyle只能用于获取页面元素的样式,不能用来设置相关值。
如果要
设置相应值,应使用style

转载地址:http://gmpj.baihongyu.com/

你可能感兴趣的文章
NFS的常用挂载参数
查看>>
NFS网络文件系统
查看>>
NFS远程目录挂载
查看>>
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
NFV商用可行新华三vBRAS方案实践验证
查看>>
ng build --aot --prod生成文件报错
查看>>
ng 指令的自定义、使用
查看>>
ng6.1 新特性:滚回到之前的位置
查看>>
nghttp3使用指南
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(一)—— 组件介绍
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + Tomcat + SpringBoot 部署项目
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>