如何获取使用JavaScript的元素的背景颜色? [英] How to get the background color of an element using javascript?

查看:91
本文介绍了如何获取使用JavaScript的元素的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得任何元素的背景颜色,使用javascript说Div。我试过: -

How can i get the background color of any element, say Div, using javascript. I tried:-

<html>
    <body>
        <div id="myDivID" style="background-color: red">shit happens</div>
        <input type="button" value="click me" onclick="getColor();">
    </body>

    <script type="text/javascript">
        function getColor(){
            myDivObj = document.getElementById("myDivID")
            if ( myDivObj ){
                alert ( 'myDivObj.bgColor: ' + myDivObj.bgColor ); // shows: undefined
                alert ( 'myDivObj.backgroundcolor: ' + myDivObj.backgroundcolor ); // shows: undefined
                //alert ( 'myDivObj.background-color: ' + myDivObj.background-color ); // this is not a valid property :)
                alert ( 'style:bgColor: ' + getStyle ( myDivObj, 'bgColor' ) ); //shows: undefined
                alert ( 'style:backgroundcolor: ' +  getStyle ( myDivObj, 'backgroundcolor' ) ); // shows:undefined:
                alert ( 'style:background-color: ' +  getStyle ( myDivObj, 'background-color' ) );  // shows: undefined
            }else{
                alert ( 'damn' );
            }
        }
        /* copied from `QuirksMode`  - http://www.quirksmode.org/dom/getstyles.html - */
        function getStyle(x,styleProp)
        {
            if (x.currentStyle)
                var y = x.currentStyle[styleProp];
            else if (window.getComputedStyle)
                var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
            return y;
        }
    </script>
</html>


推荐答案

与所有包含连字符的css属性一样, JS中的名字是删除连字符,并使下面的字母大写: backgroundColor

As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor

alert(myDiv.style.backgroundColor);

这篇关于如何获取使用JavaScript的元素的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆