【问题标题】:Color changing using jquery使用jquery改变颜色
【发布时间】:2015-08-28 12:47:05
【问题描述】:
<div id="Button" ><a href="#">Button</a>
</div>
<div class="thumb" >Thumb</div>

-------------------------------

$('.thumb').addClass('new').css("background-color", "yellow");
callmeman();
$('#Button').click(function () {
    callmeman();
});

function callmeman(){
     if ($('.thumb').hasClass('new').css("background-color"," yellow")) {
         $('.thumb').css("background-color", "red");
     } else {
         $('.thumb').css("background-color", "yellow");
     }
 }

我想如果我点击按钮然后它检查拇指是否是黄色然后它会变成红色,如果我再次点击它会检查它的红色然后变成黄色等等..

还有其他方法可以调用我这样做的函数: callmeman();

【问题讨论】:

    标签: jquery html colors


    【解决方案1】:

    您可以查看hasClass() 函数和css() 函数。 hasClass 函数不返回 jQuery 对象。 if 语句正在寻找 TRUE/FALSE 值。

    $('.thumb').addClass('new').css("background-color", "yellow");
    callmeman();
    $('#Button').click(callmeman);
    
    function callmeman(){
         if ($('.thumb').hasClass('new') && $('.thumb').css("background-color") == 'yellow') {
             $('.thumb').css("background-color", "red");
         } else {
             $('.thumb').css("background-color", "yellow");
         }
     }
    

    【讨论】:

      【解决方案2】:

      我建议你创建 2 个类,即

      .yellowClass {
          background-color: yellow;
      }
      
      .redClass {
          background-color: red;
      }
      

      然后使用.toggleClass()方法

      根据类的存在或状态参数的值,从匹配元素集中的每个元素中添加或删除一个或多个类。

      脚本

      $('.thumb').addClass('new yellowClass');
      function callmeman() {
          $('.thumb').toggleClass('yellowClass redClass');
      }
      

      【讨论】:

        【解决方案3】:

        创建两个 css 类:

        .yellow{
         background-color : #FFFF00
        }
        
        .red{
         background-color : #FF0000
         }
        

        最初添加黄色类

        $('.thumb').addClass('yellow');
        

        点击时,只需像这样切换类

        $('#Button').click(callmeman);
        function callmeman(){
         $('.thumb').toggleClass('yellow red');
        }
        

        【讨论】:

          【解决方案4】:

          HTML

          <button id="button">button</button>
          <div id="thumb" class="yellowBackground">thumb</div>
          

          CSS

          .yellowBackground {
              background-color: yellow;
          }
          .redBackground {
              background-color: red;
          }
          

          JS(使用 jQuery)

          $(function() {
              $("#button").click(function() {
                  changeThumb();
              });
          });
          
          function changeThumb() {
              $("#thumb").toggleClass("yellowBackground redBackground");
          }
          

          【讨论】:

            猜你喜欢
            • 2011-05-07
            • 2014-11-02
            • 2011-05-16
            • 2014-01-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-23
            • 1970-01-01
            相关资源
            最近更新 更多