流星点击更改背景颜色

时间:2020-08-08 10:51:22

标签: javascript html css meteor

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
}

2 个答案:

答案 0 :(得分:0)

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

  $(".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>

答案 1 :(得分:-1)

我发现这也对我有用。你怎么了?

  'click .toggleBackground': (e) => {
    if(e.currentTarget.style.backgroundColor  === 'yellow'){
      e.currentTarget.style.backgroundColor  = 'white'
    } else {
      e.currentTarget.style.backgroundColor  = 'yellow'
    }
  }