如何使用 JavaScript 更改 div backgroundColor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1874560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JavaScript to change div backgroundColor
提问by lanqy
The HTML below:
下面的 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>
When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS :hover)
当鼠标悬停在 div 的内容上时,它的 backgroundColor 和 h2(在这个 div 内)backgroundColor 会发生变化(就像 CSS :hover 一样)
I know this can use CSS (:hover) to do this in modern browser but IE6 does't work.
我知道这可以使用 CSS (:hover) 在现代浏览器中执行此操作,但 IE6 不起作用。
How to use JavaScript (not jQuery or other JS framework) to do this?
如何使用 JavaScript(不是 jQuery 或其他 JS 框架)来做到这一点?
Edit:how to change the h2 backgroundColor too
编辑:如何更改 h2 backgroundColor
回答by Jacob Relkin
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';
};
回答by nemisj
Adding/changing style of the elements in code is a bad practice. Today you want to change the background colorand tomorrow you would like to change background imageand after tomorrow you decided that it would be also nice to change the border.
在代码中添加/更改元素的样式是一种不好的做法。今天你想改变背景颜色,明天你想改变背景图像,明天你决定改变边框也很好。
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
每次只因为设计需求变化而编辑代码是一种痛苦。另外,如果你的项目会增长,更改js文件会更加痛苦。更多的代码,更多的痛苦。
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
尽量避免使用硬编码样式,这将节省您的时间,如果您做得对,您可以要求为其他人执行“更改颜色”任务。
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
因此,您可以在节点上添加/删除 CSS 类,而不是更改样式的直接属性。在您的特定情况下,您只需要为父节点执行此操作 - “div”,然后通过 CSS 设置子节点的样式。因此无需将特定的样式属性应用于 DIV 和 H2。
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
再推荐一个点。尽量不要连接硬编码的节点,而是使用一些语义来做到这一点。例如:“将事件添加到所有具有“内容”类的节点。
In conclusion, here is the code which I would use for such tasks:
总之,这是我将用于此类任务的代码:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
而你的 CSS 应该是这样的:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
回答by catchmeifyoutry
Access the element you want to change via the DOM, for example with document.getElementById()or via thisin your event handler, and change the style in that element:
通过 DOM 访问要更改的元素,例如在事件处理程序中使用document.getElementById()或通过this,并更改该元素中的样式:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
编辑
You can use getElementsByTagNametoo, (untested) example:
您也可以使用getElementsByTagName,(未经测试)示例:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
回答by Vincent Ramdhanie
<script type="text/javascript">
function enter(elem){
elem.style.backgroundColor = '#FF0000';
}
function leave(elem){
elem.style.backgroundColor = '#FFFFFF';
}
</script>
<div onmouseover="enter(this)" onmouseout="leave(this)">
Some Text
</div>
回答by Las
This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hoverattribute just like with aelements.
这个可能有点奇怪,因为我真的不是一个认真的程序员,而且我在编程中发现了青霉素的发明方式 - 纯粹是意外。那么如何在鼠标悬停时更改元素?:hover像使用a元素一样使用属性。
Example:
例子:
div.classname:hover
{
background-color: black;
}
This changes any divwith the class classnameto have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox
这将更改任何div类,classname使其在鼠标悬停时具有黑色背景。您基本上可以更改任何属性。在 IE 和 Firefox 中测试
Happy programming!
编程快乐!
回答by Lizwi
It's very simple just use a function on javaScript and call it onclick
非常简单,只需在 javaScript 上使用一个函数并调用它 onclick
<script type="text/javascript">
function change()
{
document.getElementById("catestory").style.backgroundColor="#666666";
}
</script>
<a href="#" onclick="change()">Change Bacckground Color</a>
回答by G-Phys
You can try this script. :)
你可以试试这个脚本。:)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>
回答by jhurshman
If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.
如果您愿意将非语义节点插入到您的文档中,您可以通过将您的 div 包装在假 A 标签中,以仅 CSS 的 IE 兼容方式执行此操作。
<style type="text/css">
.content {
background: #ccc;
}
.fakeLink { /* This is to make the link not look like one */
cursor: default;
text-decoration: none;
color: #000;
}
a.fakeLink:hover .content {
background: #000;
color: #fff;
}
</style>
<div id="catestory">
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
</div>
回答by Jon Benedicto
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
要在没有 jQuery 或任何其他库的情况下执行此操作,您需要将 onMouseOver 和 onMouseOut 事件附加到每个 div 并更改事件处理程序中的样式。
For example:
例如:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
如果你的 h2 没有设置自己的背景,div 背景也会显示出来并着色。

