[英]change CSS property on keypress
我希望javascript代碼在按鍵時更改bat1 div的'left'屬性嗎? HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="bat1">
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
#bat1{
width: 150px;
height: 20px;
background-color: blue;
position: relative;
left: 10%;
}
您可以像這樣為按鍵添加事件處理程序
function keyfunction(){
document.getElementById("bat1").style.left = "300px";
}
document.addEventListener("keypress", keyfunction, false);
function keyfunction(){ document.getElementById("bat1").style.left = "300px"; } document.addEventListener("keypress", keyfunction, false);
#bat1{ width: 150px; height: 20px; background-color: blue; position: relative; left: 10%; }
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div id="bat1"> </div> <script src="script.js"></script> </body> </html>
當按下輸入鍵時,我剛剛完成了有條件的添加顏色。
$("button").keydown(function(e) { //when the key(enter) is pressed Sets the color ... if(e.which === 13) { $(this).css("background-color", "green"); } }); $("button").keyup(function() { // Removes the color when any key is lifted... $(this).css("background-color", ""); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="anyclass"> I am a button </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.