首页 > 解决方案 > 点击时流星改变背景颜色

问题描述

Meteor 中的此代码需要在单击时将背景颜色更改为黄色,在再次单击时将背景颜色更改为白色,我在阅读其他解决方案后尝试了几种方法,但无法使其正常工作。

如果它是白色的,如何将颜色更改为黄色,如果它是黄色的,如何将其更改为白色。稍后我还需要在条件语句中编写其他内容。

HTML 是:

<p>{{car.carID}} <strong class="toggleBackground">{{car.plate}}</strong></P>

谢谢

'click .toggleBackground': (e) => {
    //$(e.target).addClass('yellow'); // tried with css file for no avail
    
    console.log($(e.target).css("background-color"));

//tried === rgba(255, 255, 0) instead of yellow for no avail
    if($(e.target).css('background-color') === 'yellow'){ //<<< never true
      console.log('already yellow'); //<<< never called
      $(e.target).css('background-color', 'white');
    } else {
      console.log('will make yellow');
      $(e.target).css('background-color', 'yellow');

     }

  }
.white{
    background-color: #FFFFFF
}
.red{
    background-color: yellow
}

标签: javascripthtmlcssmeteor

解决方案


请检查下面的代码,这对你有用。在这里,我使用类来检查当前应用于元素的类,并在此基础上切换类,以便当存在黄色时,它将删除该类并添加白色类,反之亦然。

  $(".toggleBackground").click(
            function () {
                    if($(this).hasClass("red")){
                    $(this).removeClass("red");
                   $(this).addClass("white");
                }
                else{
                $(this).addClass("red");
                 $(this).removeClass("white");
                }
                
            }            
        );
.white{
    background-color: #FFFFFF
}
.red{
    background-color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>{{car.carID}} <strong class="toggleBackground">{{car.plate}}</strong></p>


推荐阅读