分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

js中style,currentStyle和getComputedStyle的区别以及获取css操作方法

发布时间:2023-09-06 02:28责任编辑:蔡小小关键词:jsstyle

在js中,之前我们获取属性大多用的都是ele.style.border这种形式的方法,但是这种方法是有局限性的,该方法只能获取到行内样式,获取不了外部的样式.所以呢下面我就教大家获取外部样式的方法,因为获取外部的样式存在兼容性的问题,所以后面我还会教大家解决兼容性的方法.

style:各大浏览器都兼容,能设置样式和获取样式,但是获取不了外部样式,如果写了行内没有的样式,返回的是空值

写法:ele.style.attr(这样为获取),ele.style.attr="值";

currentStyle属性和getComputedStyle属性不能设置属性,只能获取

currentStyle:该属性只兼容IE,不兼容火狐和谷歌

 写法:ele.currentStyle["attr"]或者ele.currentStyle.attr;

getComputedStyle:该属性是兼容火狐谷歌,不兼容IE

写法:window.getComputedStyle(ele,null)[attr]获取是window.getComputedStyle(ele,null).attr

下面我就贴上我的代码:

var div=document.getElementsByTagName("div")[0]; ???????if(div.currentStyle){ ???????????//IE上兼容 ???????????console.log(div.currentStyle["width"]); ???????} ???????else{ ???????????//火狐谷歌上兼容 ???????????console.log(window.getComputedStyle(div,null)["width"]); ???????}

下面呢,我写了一个兼容性的方法,大家可以参考参考:

 ???????var div=document.getElementsByTagName("div")[0]; ???????console.log(getStyle(div,"background-color")); ???????function getStyle(ele,attr){ ???????????if(window.getComputedStyle){ ???????????????return window.getComputedStyle(ele,null)[attr]; ???????????} ???????????return ele.currentStyle[attr]; ???????}

说明:在IE中获取到的颜色是16进制的,在火狐谷歌中获取的颜色是rgb模式的

js中style,currentStyle和getComputedStyle的区别以及获取css操作方法

原文地址:https://www.cnblogs.com/gxywb/p/10208256.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved