为什么我获取不到这个css样式?js原生获取css样式总结

来源:互联网 发布:听写软件 编辑:程序博客网 时间:2024/05/17 06:25

需求

简单就是获取一个css的height

(好吧 就是一个这么简单的需求)

实践

好吧 长时间的JQ 我已经对原生无能了 让我默哀3秒!!!

document.querySelector('.className').style.height;

这个果然不生效 好吧 看来我真的倒退不少!让我再哭一会!!(哭你妹 快去总结)

在学习中发现 其实js原生获取css的方法很多,上面写的就是其中一种,只不过情景不对啊!

getComputedStyle

  • 说明 一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration])

简单来说 读出你八辈祖宗的一个方法。

  • 语法 window.getComputedStyle(dom, '伪元素')

看到伪元素、我就懵逼了 我只知道伪类啊 这有神马区别?

伪元素 其实就是 ::before :: after :: first-line ::first-letter ::content 等等
伪类 :hover :link :first-child :active 等等

  • 用法
var oImg = document.getElementById('photo');window.getComputedStyle(oImg, null).height;

dom.style

  • 说明 获取元素style属性中的CSS样式, 简单说就是 能读能写 只能读你的外表

  • 语法 dom.style.样式名称

  • 用法

var oImg = document.getElementById('photo');oImg.style.height;  // 只能获取css 样式表的

currentStyle

  • 说明 返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>属性等)与getComputedStyle那个读你八辈祖宗的很像,但是不能获取伪元素。且他们获取的属性也有很大差异。

  • 语法 element.currentStyle.样式

  • 用法

var oImg = document.getElementById('photo');oImg.currentStyle.height;  // 只能获取css 样式表的

getPropertyValue和getAttribute

  • 说明 可以获取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事件来解决,具体还有其他更多的方法。

0 0
原创粉丝点击