获取元素最终的css样式
随便分享一下关于获取元素的最终属性,
写了一个小的demo;代码如下;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{margin:0;padding: 0;} .fixed{position: fixed;top: 0px;} #bos{height:500px;background-color:#EF9fB0;} #fixed{height:40px;width:100%;background-color:#7092BE;color:#fff;text-align: center;} .bottom{height:500px;width:100%;background-color:#e0f8a1; } </style> </head> <body style = "height:2000px;background:green;"> <div id = "bos"></div> <div id="fixed">当滚动条到DIV这里是 定位在TOP 当滚动条到顶部时DIV又回到文档流中</div> <div class = "bottom"></div> </body> <script type="text/javascript"> var fixedDom = document.getElementById('fixed'); var bosDom = document.getElementById('bos'); //给元素添加一个 监听addEventListener document.addEventListener('scroll',winScroll,false); function winScroll(e){ var fixedTop = fixedDom.offsetTop;//获取元素到顶部的距离 //获取元素最终的属性 // var style = window.getComputedStyle ? window.getComputedStyle(bosDom,null) : null || box.currentStyle; var bosHeight = getStyle(bosDom,"height"); //获取滚动条到窗口顶部的距离 var clientTop = document.documentElement&&document.documentElement.scrollTop // console.log(fixedTop) // console.log('元素高度'+bosHeight.substring(0,3)) if(fixedTop < clientTop){ fixedDom.classList.add("fixed"); } if(bosHeight.substring(0,3) >= clientTop){ fixedDom.classList.remove("fixed"); } } //获取元素最终生效的属性 function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } } </script> </html>
封装了一个函数:
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}

浙公网安备 33010602011771号