开发者

Inline css value in javascript

开发者 https://www.devze.com 2023-02-03 08:49 出处:网络
How would I get a css property inside javascript! ex : <style> #body{ background:red; } </style>

How would I get a css property inside javascript!

ex :

  <style>
     #body{
        background:red;
      }
  </style>

    <script>
       function valid(form){
          alert('enter');
          var test = document.getElementById('body').style.background ;
          alert(te开发者_Go百科st');
        }
     </script>
</head>
<body id="body">

On alert I am not able to get the background color!


The style property on elements only reflects the style information in the element itself (such as via the style attribute in the markup), not anything applied by style rules. To get those, you'd need getComputedStyle:

var foo = document.getElementById('foo');
display("foo's background color is: " +
      window.getComputedStyle(foo, null).getPropertyValue('background-color'));

Live example


Off-topic: Some of this stuff is made easier by libraries such as jQuery, Prototype, YUI, Closure, or any of several others.

0

精彩评论

暂无评论...
验证码 换一张
取 消