How to use JavaScript to change div backgroundColor

前端 未结 9 1980
萌比男神i
萌比男神i 2020-11-29 05:26

The HTML below:

some title here

some content here

9条回答
  •  既然无缘
    2020-11-29 06:01

    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.

提交回复
热议问题