[英]Change img source when key is pressed and back when released
我要完成的工作:當用戶按下空格鍵時,圖像源應從spacebar.png
更改為spacebar_pressed.png
。 當用戶釋放密鑰時,圖像應更改回默認值。
我到處環顧四周,嘗試了幾種可能性,但沒有一種可行。 請記住,我對Java不太滿意。
HTML:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/spacebar.js"></script>
</head>
<body>
<h1>Spacebar Simulator 2017</h1>
<img src="assets/spacebar.png" id="spacebar">
</body>
</html>
這是我嘗試過的最新代碼:
$("#spacebar").on("keydown", function(e){
var code = e.keyCode;
if(code == 32){
document.getElementById("spacebar").src="../assets/spacebar_pressed.png";
}
});
您可以組合keypress
和attr
功能來完成此任務。
在回調中,你有你的事件對象,它的屬性, which
是鍵代碼,它代表被按下的鍵。 空格鍵的keyCode為32。
當在DOM上釋放密鑰時,URL再次顯式更改。
$(function() { var myRealUrl = "http://hammerjs.github.io/assets/img/stackoverflow-icon.svg"; $("body").on("keydown", function(e) { if (e.which == 32) { $("#spacebar").attr("src", "https://i.stack.imgur.com/CE5lz.png"); console.log('pressed'); } }); $("body").keyup(function(e) { if (e.which == 32) { $("#spacebar").attr("src", myRealUrl); console.log('released'); } }); });
/*Demo Use*/ img { max-height: 100px; max-width: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://hammerjs.github.io/assets/img/stackoverflow-icon.svg" id="spacebar" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.