簡體   English   中英

使用jQuery更改div的背景色

[英]Using jQuery to changing background colour of a div

當用戶按下CMY時,我試圖更改div的背景顏色。 我需要使用keypress方法,但是由於某些原因,我的代碼無法正常工作。

 $(document).ready(function() { $(document).keypress(function(event) { if (event === 99) { $(".light").css('background-color', "#00ffff"); } else if (event === 121) { $(".light").css('background-color', "#00ffff"); } else if (event === 109) { $(".light").css('background-color', "#00ffff"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="light"></div> 

您需要使用event.which來確定按下了哪個鍵。 這是工作代碼:

 $(document).ready(function() { $(document).keypress(function(event) { if (event.which === 99) { $(".light").css('background-color', "#00ffff"); } else if (event.which === 121) { $(".light").css('background-color', "#00ffff"); } else if (event.which === 109) { $(".light").css('background-color', "#00ffff"); } }); }); 
 div.light { width: 50px; height: 50px; background-color: black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="light"></div> 

您需要使用keypress事件中的which值。 我還建議您使用switch -statement。

 $(document).ready(function() { $(document).keypress(function(e) { var color = null; switch (e.which || e.keyCode || 0) { // Cover all cases case 99: // Key - C color = '#00FFFF'; break; case 109: // Key - M color = '#FF00FF'; break; case 121: // Key - Y color = '#FFFF00'; break; default: color = '#FFFFFF'; } $('.light').css('background-color', color); }); }); 
 .light { width: 95vw; height: 95vh; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="light"></div> 


感謝smarxjQuery和which的注意

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM