Change color of button during keypress

后端 未结 3 737
终归单人心
终归单人心 2021-01-24 21:49

I want to change the color of a


when it is clicked by a mouse or while pressing the enter key.<

相关标签:
3条回答
  • 2021-01-24 22:24

    Try This

    .clicked{
    background:#fff !important;
    }
    
    $('.button').keydown(function(e){
          if(e.which == 13){
               $(this).addClass('clicked');
            }
     e.preventDefault();
      });
    
    0 讨论(0)
  • 2021-01-24 22:27

    Please try following code

               $('.button').keypress(function(e){
                  if(e.which == 13){
                      $(this).css('background-color','#FFF');
                  }
                });
    
                $('.button').keyup(function(e){
                  if(e.which == 13){
                      $(this).css('background-color','');
                  }
                });
    
    0 讨论(0)
  • 2021-01-24 22:33

    Use a combination of keypress/keyup to toggle the color:

    $("button").keydown(function(e) {
        // Sets the color when the key is down...
        if(e.which === 13) {
        	$(this).css("background-color", "red");
        }
    });
    $("button").keyup(function() {
        // Removes the color when any key is lifted...
        $(this).css("background-color", "");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button>
    Test
    </button>

    0 讨论(0)
提交回复
热议问题