小编典典

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

html

如何div使用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) {

      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.log('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>

阅读 343

收藏
2020-05-10

共1个答案

小编典典

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

alert(myDiv.style.backgroundColor);
2020-05-10