<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS原生获取style属性值</title> <style> #div { width: 200px; height: 200px; background-color: #ff00ff; border: 20px solid #ffff00; margin: 30px auto; padding-top: 100px; font-size: 30px; text-align: center; } #div:after{ content: ':after'; display: block; } </style> <script src="http_code.jquery.com_jquery-2.0.0.js"></script> </head> <body> <div id="div" style='display: block;'> JS原生获取style属性值 </div> <script> var div=document.getElementById('div'); var $div=$('#div'); window.onload=function(){ //console.log(div.style) //style(); //不同浏览器,显示效果不同 GetComputedStyle(); //IE自己 //CurrentStyle(); //hacker() } //原生js直接使用style属性获取css样式 function style(){ //返回CSSStyleDeclaration对象,是一个属性集合,里面的属性的值都为空 console.log(div.style) //直接使用style属性无法访问到内嵌,外部的css样式,只能访问内联样式的css样式 console.log('内嵌,外部width.....'+div.style.width) console.log('内联display.....'+div.style.display) //直接使用jq获取css的样式 console.log('jq.....'+$div.css('width')) } function GetComputedStyle(){ // window.getComputedStyle(Obj,Pseudo-classes).property var gcs=window.getComputedStyle(div,null); var gcs_a=window.getComputedStyle(div,'after'); //console.log('gcs_a.....'+gcs_a.display) //返回CSSStyleDeclaration对象,有值的,是只读的 console.log(gcs) //使用getComputedStyle获取内嵌,内联,外部的css样式 console.log('gcs.....'+gcs.width) //多属性的样式下chrome能获取,firefox获取不到 console.log('border....'+gcs.border) console.log('borderColor....'+gcs.borderColor) console.log('paddingTop....'+gcs.paddingTop) //jq使用的css选择器同理 console.log('$border.....'+$div.css('border')) console.log('$borderColor....'+$div.css('border-color')) } function CurrentStyle(){ Obj.currentStyle.property div.currentStyle.width } function hacker(){ if(window.getComputedStyle){ GetComputedStyle() }else if(Object.currentStyle){ CurrentStyle() }else { return false } } </script> </body> </html>
原生JS获取内嵌,外部css样式,使用style只能直接获取内联style的属性值
最新推荐文章于 2022-11-03 09:47:29 发布