博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript 获取和设置CSS的当前属性
阅读量:7229 次
发布时间:2019-06-29

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

hot3.png

一.下面是获取CSS属性值的一种方式

function getCssValue(element,cssName){    var cssValue = '';    var CStyle=document.defaultView?document.defaultView.getComputedStyle(element,null):element.currentStyle;   //getComputedStyle(element,null) 第二个参数是伪类 如getComputedStyle(element,':hover')  if(cssName.toLowerCase()=='opacity' && navigator.userAgent.toLowerCase().indexOf('msie') != -1)  {	cssValue = elem.currentStyle.filter.replace('opacity=',''); //IE透明度问题  }  else  {	cssValue= CStyle['opacity'];  }         return cssValue;}

上面的CStyle等于获取到当前css对象CSSStyleDeclaration

属性值的获取方式有2中,一种是驼峰式,另一种是直接获取CSS

CStyle.paddingLeft   stringCStyle['padding-left'] string还可以使用CStyle.getPropertyValue('padding-left'); string

二.设置Css的方式,在传统的css操作中,属性的设置很方便

elem.style.backgroundColor= 'red';//或者elem.setAttribute('style','background-color:red;border:1px solid black;');//或者divStyle.cssText = 'background-color:red;border:1px solid black;height:100px;width:100px;';//或者以下不常用的方式var bodyStyle = window.getComputedStyle(document.body,null);bodyStyle.setProperty('backgroundColor','red');

三.对于html5而言,新的api设计非常优秀,下面是如何监听测试说事件的

var e = document.getElementById("animation"); e.addEventListener("animationstart", cssAnimListener, false);  e.addEventListener("animationend", cssAnimListener, false);  e.addEventListener("animationiteration", cssAnimListener, false);  //监听过渡事件 $("body").on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){     $("div#trasit").css("transition", "none");   });

另外在Css中引入了Styleheets和Styleheet对象,可通过 document.stylesheets获得,Styleheet有着丰富的api,可动态设置css文件属性和css规则,这里不再细说,有兴趣的读者可以自行查询。

四.对于html5中自适应布局,通常也有很好的监听事件

var mql = window.matchMedia('@media all and (max-width: 700px)'); // 指定回调函数  mql.addListener(mqCallback);  // 撤销回调函数  mql.removeListener(mqCallback);  function mqCallback(mql) {        if (mql.matches) {          // 宽度小于等于700像素        } else {          // 宽度大于700像素      } }

转载于:https://my.oschina.net/ososchina/blog/346627

你可能感兴趣的文章
iptables详解
查看>>
Protostuff 介绍
查看>>
一张图看懂开源许可协议,开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别...
查看>>
参数验证其实可以更简明一点
查看>>
Set up Mule runtime env with mule-standalone-3.6.0
查看>>
Linux基础-linux命令:csplit
查看>>
core_framework —— 基于libev的轻量级lua网络开发框架
查看>>
回到顶部
查看>>
DES/3DES(TripleDES)加密、解密测试数据
查看>>
Maven项目标准目录结构
查看>>
Tomcat 系统架构与设计模式,第 1 部分: 工作原理
查看>>
Hadoop输出参数信息详解(16)
查看>>
ERROR 2002 (HY000): Can't connect to local MySQL错误
查看>>
Java版冒泡排序法
查看>>
关于FB4.6插件安装后默认语言环境的更改问题
查看>>
免费分区助手
查看>>
Javascript通过Name调用Function
查看>>
统计当前在线用户数量
查看>>
IntelliJ IDEA 乱码解决方案 (项目代码、控制台等)
查看>>
PHP项目记录
查看>>