How to use JavaScript to change div backgroundColor

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

The HTML below:

some title here

some content here

相关标签:
9条回答
  • 2020-11-29 06:00

    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.

    <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>
    
    0 讨论(0)
  • 2020-11-29 06:01
    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';
    };
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题