2017-11-07 14 views
0

ユーザーがボタンをクリックすると、色が青色から赤色に変わり、元の色に戻ります。 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>

+0

のようなもののためにトグルクラスの機能を使用することができますtoggleClass( "class")を使用できます。 – DHLopez

+0

「より良い方法」を定義する – j08691

答えて

0

あなたがこれを行うことが一つの方法は、赤の背景色のためのクラスを追加し、そのクラスをトグルです:

jqueryのを使用して

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

0

とtoggleClass :

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

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

0

あなたは、CSS(代わりにボタンタグの)クラス、あなたを作る場合は、この

clicked = true; 
 
     $(document).ready(function(){ 
 
      $("button").click(function(){ 
 
        $(this).toggleClass('red'); 
 
        $(this).toggleClass('blue'); 
 
        
 
      }); 
 
     });
button{ 
 
     
 
     height:100px; 
 
     width:150px; 
 
    } 
 
    
 
    .red 
 
    { 
 
    background-color:red; 
 
    } 
 
    
 
    .blue 
 
    { 
 
    background-color:blue; 
 
    }
<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>

関連する問題