背景颜色变化

时间:2021-04-21 08:18:32

标签: javascript html css

在第一次点击时更改背景颜色(通过 this 关键字),第二次点击后背景颜色应更改回之前在 JavaScript 中的颜色

<div class="tag-box-cover" id="tag_box_cover">`my main heading`
   <div class="label-text">Trivandrum</div>`content`
       <div class="btn-wrap">`internal div`
           <div class="tag-btn">
               <a data-id="15" onclick="h_bg_color()" class="tag-anchor add-category-to-setup has-parent">`onclick button`
                   <i class="material-icons"></i>
               </a>
           </div>
       </div>
 </div>

1 个答案:

答案 0 :(得分:0)

您可以简单地添加默认背景颜色并在单击时切换具有更高特异性的 CSS 类,该类包含另一种背景颜色,如下所示:

document.querySelector('#tag_box_cover')
.addEventListener('click', e => {
  e.target.classList.toggle('bg-blue');
});
.tag-box-cover {
  height: 100px;
  width: 100px;
  background-color: red;
}

#tag_box_cover.bg-blue {
  background-color: blue;
}
<div class="tag-box-cover" id="tag_box_cover"></div>