如何使用JavaScript来改变div backgroundColor [英] How to use JavaScript to change div backgroundColor

查看:210
本文介绍了如何使用JavaScript来改变div backgroundColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下HTML:

<div id="catestory">

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

</div>

当鼠标悬停在div的内容上时,它的backgroundColor和h2(在这个div中)backgroundColor变化(只是比如CSS:hover)

When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS :hover)

我知道这可以使用CSS(:hover)在现代浏览器中执行此操作,但IE6不起作用。

I know this can use CSS (:hover) to do this in modern browser but IE6 does't work.

如何使用JavaScript(不是jQuery或其他JS框架)来做这个?

How to use JavaScript (not jQuery or other JS framework) to do this?

编辑:如何更改h2 backgroundColor too

推荐答案

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

这篇关于如何使用JavaScript来改变div backgroundColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆