javascript更改多个类的元素的图像

时间:2018-06-17 10:04:01

标签: javascript html html5

这是我的HTML

    <td><div class="wrapper-top-right">
       <div class="container">
          <div class="top"></div>
             <div class="bottom">
               <div class="left">
                  <div class="details">
                    <div class="text-center" style="font-size:20px; color:white;" id="details-1"></div>
                    <br>
                  </div>    
               </div>
             </div>
             <div class="inside">
             <div class="contents content-corner" id="content-1"></div>
          </div>
        </div>
      </div>
    </td>

这是我的CSS

   .wrapper-top-right .container .top {
      height: 70%;
      width: 100%;
      background-image: url('images/go.gif');
      background-repeat: no-repeat;
      -webkit-background-size: 100%;
      -moz-background-size: 100%;
      -o-background-size: 100%;
    }

如何使用javascript从.wrapper-top-right .container .top更改图像?

1 个答案:

答案 0 :(得分:0)

使用querySelector('.wrapper-top-right>.container>.top')

function func(){
document.querySelector('.wrapper-top-right>.container>.top').style.backgroundImage = "url('https://material.angular.io/assets/img/examples/shiba2.jpg')";
}
   .wrapper-top-right .container .top {
      height: 100px;
      width: 100px;
      background-image: url('https://material.angular.io/assets/img/examples/shiba1.jpg');
      background-repeat: no-repeat;
      -webkit-background-size: 100%;
      -moz-background-size: 100%;
      -o-background-size: 100%;
    }
    <td><div class="wrapper-top-right">
       <div class="container">
          <div class="top"></div>
             <div class="bottom">
               <div class="left">
                  <div class="details">
                    <div class="text-center" style="font-size:20px; color:white;" id="details-1"></div>
                    <br>
                  </div>    
               </div>
             </div>
             <div class="inside">
             <div class="contents content-corner" id="content-1"></div>
          </div>
        </div>
      </div>
    </td>
<button onclick="func()">change image</button>