遇到的问题(css设置background 和 JS获取元素属性)

问题概述:直接通过id设置background设置无效

布局

<div id="bnts">
    <span class="on"></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>
View Code

CSS

    #bnts span {
        cursor: pointer;
        float: left;
        border: 1px solid #FFF;
         10px;
        height: 10px;
        border-radius: 50%;
        background: #333;
        margin-right: 5px;
    }
    #bnts .on {
        background: #FFF;
    }
View Code

问题描述:按照方法一设置的background有效,而按照方法二设置background设置无效。

方法一、 #bnts .on { background: #FFF; } 

方法二、  .on { background: #FFF; } 

原因和解决方法:


 问题概述:在JS无法通过*.style.width 获取元素宽度属性

布局: <div id="imgs"></div> 

CSS:

    #imgs {
        position: absolute;
        height: 400px;
         4200px;
        z-index: 1;
        top: 100px;
        left: 200px;
    }
View Code

问题描述:在JS无法直接通过 *.style.width获取元素的属性。

原因和解决方法:

原因:*.style.width 只能获取写在html里面的css样式。(内联样式)

解决方法:

1、设置需要用的样式为内联样式。例如:

    HTML  <div id="imgs" style="200px"></div>           

    JS  var width = document.getElementById("img").style.width; 

2、低版本IE中,使用currentStyle, 例如:

    HTML  <div id="imgs"></div>        

    JS   var imgs = document.getElementById("imgs");     var width = imgs.currentStyle.width; 

3、高版本IE和FF,解决办法为:

    HTML  <div id="imgs"></div>         

    JS   var imgs = document.getElementById("imgs");     var width = document.defaultView.getComputedStyle(imgs, null).width 

4、解决浏览器兼容性的办法:

1             var imgs = document.getElementById("imgs");
2             var len = imgs.currentStyle.width;
3             if(imgs.currentStyle){
4                 len = imgs.currentStyle.width;
5             }else {
6                 len = document.defaultView.getComputedStyle(imgs, null).width;
7             }
View Code
原文地址:https://www.cnblogs.com/hemi/p/4009101.html