更改点击事件

时间:2017-11-07 19:22:45

标签: jquery html

我有一个html按钮,当用户点击按钮时,它会将颜色从蓝色变为红色并返回。在jQuery中有更好的方法吗?



clicked = true;
$(document).ready(function() {
  $("button").click(function() {
    if (clicked) {
      $(this).css('background-color', 'red');
      clicked = false;
    } else {
      $(this).css('background-color', 'blue');
      clicked = true;
    }
  });
});

button {
  background-color: blue;
  height: 100px;
  width: 150px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Press</button>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

一种方法是为红色背景颜色添加一个类并切换该类:

$("button").click(function(){
  $(this).toggleClass("redButton");
});   
button{
    background-color: blue;
    height:100px;
    width:150px;
}
.redButton { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Press</button>

答案 1 :(得分:0)

使用jquery和toggleClass:

&#13;
&#13;
$("button").click(function(){
  $('.btn').toggleClass('toggled');
})
&#13;
.btn{
			background-color: blue;
      padding: 10px;
      color: white;
		}
.toggled{
  background-color: red;
}
&#13;
<button type="button" class="btn">Press</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以像这样使用切换类功能

&#13;
&#13;
clicked = true;
        $(document).ready(function(){
            $("button").click(function(){
                    $(this).toggleClass('red');
                    $(this).toggleClass('blue');
                  
            });
        });
&#13;
button{
       
        height:100px;
        width:150px;
    }
    
    .red
    {
    background-color:red;
    }
    
    .blue
    {
    background-color:blue;
    }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <head>
        <title>Button Fun</title>
        <script src = 'bower_components/jquery/dist/jquery.js'></script>
        <script type="home.js"></script>
        <link rel="stylesheet" type="text/css" href="styles.css"/>
      
    </head>
    <body>
    
        <button class="blue">Press</button>
    
    </body>
    </html>
&#13;
&#13;
&#13;