How to use JavaScript to change div backgroundColor

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

The HTML below:

some title here

some content here

some title here

some content here

some title here

some content here

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

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

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

Edit:how to change the h2 backgroundColor too

回答1:

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'; }; 


回答2:

Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and 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.

Try to eliminate use of hard coded styles, this will save you time and, if you do it write, 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.

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'.

As a summery I put here 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:

.content {     background-color: blue; }  .content.Hover{     background-color: red; }  .content.Hover h2{     background-color : yellow; } 


回答3:

Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:

document.getElementById("MyHeader").style.backgroundColor='red'; 

EDIT

You can use getElementsByTagName too, (untested) example:

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 


回答4:

Some Text


回答5:

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 :hover attribute just like with a elements.

Example:

div.classname:hover {     background-color: black; } 

This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox

Happy programming!



回答6:

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.

 


回答7:

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.

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.



回答8:

You can try this script. :)

              Div BG color

some title here

some content here

some title here

some content here

some title here

some content here



回答9:

It's very simple just use a function on javaScript and call it onclick

   Change Bacckground Color 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!