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

iqih9akk  于 2023-05-12  发布在  Java
关注(0)|答案(8)|浏览(156)

如何使用JavaScript获取任何元素(如<div>)的背景颜色?我试过:

<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>
t40tm48m

t40tm48m1#

获取号码:

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

示例:

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

dxxyhpgq2#

与所有包含连字符的css属性一样,它们在JS中的对应名称是删除连字符并使以下字母大写:backgroundColor

alert(myDiv.style.backgroundColor);
ffdz8vbo

ffdz8vbo3#

简单的解决方案

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

现在,背景颜色存储在新变量中。
https://jsfiddle.net/7q1dpeo9/1/

t98cgbkg

t98cgbkg4#

使用jQuery:

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

带原型:

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

纯JS:

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

bfrts1fy5#

这取决于您需要的div中的哪种样式。这是在CSS中定义的背景样式,还是通过javascript(inline)添加到当前节点的背景样式?
如果是CSS样式,则应该使用计算样式。就像你在getStyle()中做的那样。
对于内联样式,您应该使用node.style引用:x.style.backgroundColor ;
还要注意,您通过使用camelCase/non hyphen引用来选择样式,因此不是background-color,而是backgroundColor;

llmtgqce

llmtgqce6#

这对我很有效:

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");
oxalkeyp

oxalkeyp7#

使用JQuery

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

bqucvtff8#

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

<html>
<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>

这是一把能用的小提琴。https://jsfiddle.net/cdgpts9n/

相关问题