一.下面是获取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像素 } }