大家好,我有一个div,如下:
<div class="mycss">aaa</div>mycss里面怎么定义的我并不知道,且也不知道mycss这个名字,即上述代码为动态生成。页面展示出来,发现div的背景是红色,现在我已拿到div这个元素的对象,如何得到它的背景呢?divObj.style.background不行(返回为""),请指教,谢谢~~

解决方案 »

  1.   

    try
    function CurrentStyle(element){
    return element.currentStyle || document.defaultView.getComputedStyle(element, null);
    };
    alert(CurrentStyle(div).backgroundColor)
      

  2.   

    如果是表格tr,td之类是:
    divObj.style.bgColor其他的是
    divObj.style.backgroundColor有时候也有可能会取不到,要用到另一个方法
      

  3.   

    楼上的各位  你们测试了吗    还正解  正解的
    ie6 ff下 测试是取不到值 的
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title></title>
    <style type="text/css">
    .cc{height:200px;width:200px;background-color:#ff0000}
    </style>
    <body ><div id="div" class="cc"></div>
    <script language="javascript">
    window.onload =function(){
    alert(document.getElementById('div').style.backgroundColor)
    }
    </script></body>
    </html>
      

  4.   

    这个是正确的 获取当前样式<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title></title>
    <style type="text/css">
    .cc{height:200px;width:200px;background-color:#FF0000}
    </style>
    <body >
    <div id="div" class="cc"></div>
    <script language="javascript">
    function CurrentStyle(element){
    return element.currentStyle || document.defaultView.getComputedStyle(element, null);
    };
    window.onload =function(){
    alert(CurrentStyle(document.getElementById('div')).backgroundColor)
    }
    </script>
    </body>
    </html>
      

  5.   

    多谢各位,,貌似只有一楼的是可以的
    return element.currentStyle || document.defaultView.getComputedStyle(element, null);
    前一半是IE的,后一半是FF的。
    再次谢谢各位热心相助~~