[英]Using jQuery to changing background colour of a div
当用户按下C , M或Y时,我试图更改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>
感谢smarx对jQuery和which的注意 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.