仍是本身遇到的一个坑的总结吧!与其说是坑不如说本身学艺不精,让我先哭一会!!css
简单就是获取一个css的heightdom
(好吧 就是一个这么简单的需求)学习
好吧 长时间的JQ 我已经对原生无能了 让我默哀3秒!!!code
document.querySelector('.className').style.height;
这个果真不生效 好吧 看来我真的倒退很多!让我再哭一会!!(哭你妹 快去总结)对象
在学习中发现 其实js原生获取css的方法不少,上面写的就是其中一种,只不过情景不对啊!事件
简单来讲 读出你八辈祖宗的一个方法。图片
看到伪元素、我就懵逼了 我只知道伪类啊 这有神马区别?element
伪元素 其实就是 ::before :: after :: first-line ::first-letter ::content 等等
伪类 :hover :link :first-child :active 等等get
var oImg = document.getElementById('photo'); window.getComputedStyle(oImg, null).height;
说明 获取元素style属性中的CSS样式, 简单说就是 能读能写 只能读你的外表io
语法 dom.style.样式名称
用法
var oImg = document.getElementById('photo'); oImg.style.height; // 只能获取css 样式表的
说明 返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>
属性等)与getComputedStyle
那个读你八辈祖宗的很像,可是不能获取伪元素。且他们获取的属性也有很大差别。
语法 element.currentStyle.样式
用法
var oImg = document.getElementById('photo'); oImg.currentStyle.height; // 只能获取css 样式表的
说明 能够获取CSS样式申明对象上的属性值(直接属性名称),
getPropertyValue能够不用驼峰,直接用其属性名
getAttribute主要是为了兼容IE获取属性值,须要驼峰的写法
语法
getPropertyValue("background-color")
getAttribute("backgroundColor")
用法
var oImg = document.getElementById('photo'); var oStyle = oImg.currentStyle? oImg.currentStyle : window.getComputedStyle(oImg, null); oStyle.getPropertyValue("background-color") oStyle.getAttribute("backgroundColor")
若是我想获取某个属性值能够 好比高度 ?
(dom.currentStyle? dom.currentStyle : window.getComputedStyle(dom, null)).height;
若是是复合的某个属性获取?
(oImg.currentStyle? oImg.currentStyle : window.getComputedStyle(oImg, null)).getPropertyValue("background-color")
若是我想给这个属性从新设置这个高度?
能够先用上面方法取到,而后用
dom.style.height = XX + 'px';
若是是复合的属性值,请注意是驼峰的写法!
其实在看了这些之后,我用了上面的这个方法我依然没有获取到这个图片的高度?为何啊 ?
由于图片存在一个加载的问题,你刚进来获取固然没法获取到? 其实能够用onload事件来解决,具体还有其余更多的方法。