下面的 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/