javascript - 如何使用JavaScript改变div背景颜色

标签 javascript background-color

下面的 HTML:

<div id="category">

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

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

如何使用 JavaScript(不是 jQuery 或其他 JS 框架)来执行此操作?

编辑:如何更改 h2 背景颜色

最佳答案

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 - 如何使用JavaScript改变div背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1874560/

相关文章:

javascript - 提取 iframe 内的脚本

javascript - jQuery :contains not working in ie7 (jQuery 1. 3.5)

css - 如何在CSS3中创建这种渐变背景?

css - 是否有 CSS 方法/hack 来指定基于平台的背景颜色(即 mac vs pc)

javascript - 从 jQuery 对象获取值数组

javascript - On Height CSS 响应性

menu - 更改 Gantry v4 菜单颜色

css - 自定义输入背景错误 ["text"] CSS

javascript - 如何在我的 ember View 中绑定(bind)到 bootstrap 的模态事件?

html - 为什么我的背景颜色在我的 imgs 之上?