2009-12-11 20 views
33

¿Cómo puedo obtener el color de fondo de cualquier elemento, digamos Div, utilizando javascript. He intentado: -¿Cómo obtener el color de fondo de un elemento usando javascript?

<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> 
+6

Tenga en cuenta que la respuesta aceptada (en la actualidad) sólo funcionará bajo un conjunto muy restringido de circunstancias. – NickFitz

Respuesta

32

Al igual que con todas las propiedades CSS que contienen guiones, sus nombres correspondientes en JS es eliminar el guión y hacer la siguiente letra mayúscula: backgroundColor

alert(myDiv.style.backgroundColor); 
+1

¡Maldición! eso fue muy fácil :) –

+0

David, por favor, hágamelo saber por qué 'getStyle' se usa en' http: // www.quirksmode.org/dom/getstyles.html', cuando era tan fácil obtener la propiedad de estilo. –

+0

y la página a la que se vincula tiene algunas descripciones en sí misma sobre lo que es bueno. para mozilla, por ejemplo, usa 'getComputedStyle', que no es tanto lo que se especifica en la hoja de estilo, sino más bien lo que se muestra, como resultado del marcado HTML * y * estilo CSS. Sin embargo, para algo tan simple como este escenario, no veo ninguna razón realmente buena para usar esa función. –

2

Usando JQuery:

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

el div antes del selector de id es un poco redundante – AutomatedTester

+0

Acepto, corregido :) – Aziz

+14

descargando y ejecutando una biblioteca de 20kb para recuperar el color de fondo de un DIV es un poco redundante;) –

11

Depende del estilo de div que necesite. ¿Es este un estilo de fondo que se definió en CSS o estilo de fondo que se agregó mediante javascript (en línea) al nodo actual?

En el caso del estilo CSS, debe usar el estilo calculado. Como lo hace en getStyle.

Con estilo en línea debe usar node.style referencia: x.style.backgroundColor;

También tenga en cuenta que elige el estilo utilizando la referencia CamelCase/non hyphen, entonces no background-color, pero backgroundColor;

13

con jQuery:

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

Con prototipo:

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

Con JS puros:

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

Obtener al número:

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

Ejemplo:

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