如何获取HTML元素的背景颜色?

96
如何使用JavaScript获取任何元素(如
)的背景颜色?我尝试过以下方法:

<html>

<body>
  <div id="myDivID" style="background-color: red">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <input type="button" value="click me" onclick="getColor();">
</body>

<script type="text/javascript">
  function getColor() {
    myDivObj = document.getElementById("myDivID")
    if (myDivObj) {
      console.log('myDivObj.bgColor: ' + myDivObj.bgColor); // shows: undefined
      console.log('myDivObj.backgroundcolor: ' + myDivObj.backgroundcolor); // shows: undefined
      //alert ( 'myDivObj.background-color: ' + myDivObj.background-color ); // this is not a valid property :)
      console.log('style:bgColor: ' + getStyle(myDivObj, 'bgColor')); //shows: undefined
      console.log('style:backgroundcolor: ' + getStyle(myDivObj, 'backgroundcolor')); // shows:undefined:
      console.log('style:background-color: ' + getStyle(myDivObj, 'background-color')); // shows: undefined
    } else {
      console.error('Error: When function "getColor();" was called, no element existed with an ID of "myDivId".');
    }
  }
  /* 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>


11
请注意,目前被接受的答案只适用于非常有限的情况。 - NickFitz
8个回答

125

获取数字:

window.getComputedStyle( *Element* , null).getPropertyValue( *CSS* );

例子:

window.getComputedStyle( document.body ,null).getPropertyValue('background-color');  
window.getComputedStyle( document.body ,null).getPropertyValue('width');  
~ document.body.clientWidth

2
null 可以不必写出来。 - Eric
3
第二个参数是一个可选属性,用于指定伪元素,因此可以安全地省略。请参阅此处的文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle - natsuozawa
1
请注意,这是一项非常昂贵的操作。请谨慎使用! - connexo

54

和所有包含连字符的 CSS 属性一样,在 JavaScript 中对应的名称是删除连字符并使下一个字母大写:backgroundColor

alert(myDiv.style.backgroundColor);

David,请问你能告诉我为什么在http://www.quirksmode.org/dom/getstyles.html中要使用getStyle,明明获取样式属性很容易啊。 - Rakesh Juyal
1
好的,你链接的页面本身就有一些描述说明它的用途。例如对于Mozilla,它使用getComputedStyle,这不仅仅是样式表中指定的内容,而且还包括HTML标记和CSS样式的结果。然而,对于这种简单的情况,我并没有看到使用该函数的真正好处。 - David Hedlund
56
style 属性仅包含在 style 属性中指定的样式或通过脚本设置的样式。在 style 元素或外部样式表中设置的样式将不会出现在其中,此时您需要为不同的浏览器使用不同的技术(通常对于除 IE 之外的所有浏览器使用标准技术),这是由 ppk 的 quirksmode 脚本来处理的。 - NickFitz

38

简单的解决方案

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

现在背景颜色存储在新变量中。

https://jsfiddle.net/7q1dpeo9/1/


4
相较于已接受的答案,这个提供了颜色值,即使是通过类分配的。 - JoSSte

26

使用 jQuery:

jQuery('#myDivID').css("background-color");

使用原型:

$('myDivID').getStyle('backgroundColor'); 

使用纯JS:

document.getElementById("myDivID").style.backgroundColor

12

这取决于您需要哪种

样式。是在CSS中定义的背景样式,还是通过javascript(inline)添加到当前节点的背景样式?

对于CSS样式,您应该使用计算样式(computed style),就像在getStyle()中所做的那样。

对于内联样式,您应该使用 node.style 引用:x.style.backgroundColor;

还要注意,通过camelCase /非连字符引用选择样式,因此不是background-color,而是backgroundColor;


9

这对我有用:

var backgroundColor = window.getComputedStyle ? window.getComputedStyle(myDiv, null).getPropertyValue("background-color") : myDiv.style.backgroundColor;

并且,更好的是:
var getStyle = function(element, property) {
    return window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(property) : element.style[property.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })];
};
var backgroundColor = getStyle(myDiv, "background-color");

2

使用 JQuery

var color = $('#myDivID').css("background-color");

选择器中 id 选择器前面的 div 有些多余。 - AutomatedTester
25
下载并执行一个20kb的库来获取DIV背景颜色有些冗余;) - David Hedlund
@David:抱歉,David,虽然我想给你+20个声望值,但是SO不允许我这样做: )。+1给你。完全同意。 - Rakesh Juyal
2
如果整个页面中唯一使用的 JavaScript 是获取背景颜色,那么它是多余的,但通常一个页面会有更多的 JavaScript 操作,这使得使用 JQuery 有些合理。 - Aziz
2
那些想要避免使用jQuery的人会发现这篇博客很有用。简而言之:你必须深入了解特定于浏览器的细节和功能。 - robert4

0

你可以在控件上绘制一个画布元素,即使不显示它,也可以获取控件中特定位置的颜色,如果它有多种颜色。

<head>
    <style>
    </style>
</head>
<body><div style="border:gray solid 2px;height:575px;width:700px;position:absolute;top:75px;right:15px;background:black;color:white;font-Family:Century SchoolBook;font-Size:18px;padding-Top:20px;" id="container101"><div id="header" style="text-Align:center">ColorPicker</div> 
    <div id="div101" style="position:absolute;top:60px;left:100px;width:500px;height:500px;"></div> 
    <canvas height="500" width="500" style="position:absolute;top:60px;left:100px;display:none;" id="canva"></canvas>

</div>

<script>
    function create(r1,g1,b1,r2,g2,b2){dv101 = 
    document.querySelector("#div101");dv101.style.background = "linear-gradient(90deg, rgb("+r1+", "+g1+", "+b1+"), rgb("+r2+", "+g2+", "+b2+"))";
    var can = document.querySelector("#canva");
    var context = can.getContext("2d");
    context.rect(0, 0, 500, 500);
    var grd = context.createLinearGradient(0,0,can.width,0);
    grd.addColorStop(0, "rgb("+r1+", "+g1+", "+b1+")");
    grd.addColorStop(1, "rgb("+r2+", "+g2+", "+b2+")");
    context.fillStyle = grd;
    context.fillRect(0,0,500,500);

    dv101.onmousemove = (event) => {
        var posx = event.clientX-dv101.offsetLeft- 
        document.querySelector("#container101").offsetLeft;
        var posy = event.clientY-dv101.offsetTop- 
        document.querySelector("#container101").offsetTop;
        console.log(posx,posy);
        var data = context.getImageData(posx,posy,1,1);
        couleur = "rgb("+data.data[0]+","+data.data[1]+","+data.data[2]+")";
        document.body.style.background=couleur;
    } return couleur;
};create(255, 0, 0, 0, 0, 255);
var arr = new Array();
function inp(x,y){
    var input1 = document.createElement('input');
    var cont = document.querySelector("#container101");
    cont.appendChild(input1);
    arr.push(input1);
    input1.type = "text";
    input1.style = "outline:none;position:absolute;top:"+y+"px;left:"+x+"px;height:30px;width:60px;background:white;color:black;";
    input1.value = 0;
    input1.onkeydown = (event) => {

        switch(event.keyCode){

        case 38:
            input1.value++;
            create(arr[0].value, arr[1].value, arr[2].value, arr[3].value, arr[4].value,arr[5].value);
            break;

        case 40:
            input1.value--;
            create(arr[0].value, arr[1].value, arr[2].value, arr[3].value, arr[4].value,arr[5].value);
            break;
        };
    }
};inp(5,60);inp(5,110);inp(5,160);inp(610,60);inp(610,110);inp(610,160);
</script>
</body>
</html>

这是一个可用的fiddle。 https://jsfiddle.net/cdgpts9n/


请提供格式化的代码。另外,这个问题是关于获取HTML元素的背景颜色,但我认为你的答案是关于用鼠标从画布中选择颜色 - 这完全是另一回事,不是吗? - Moritz Ringler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接