如何在輸入欄位被填充時更改按鈕顏色 – JavaScript?
假設我們有以下按鈕 −
<button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>
在填充以下輸入欄位後,上面按鈕的顏色應更改為 −
<input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px" onkeyup="changeTheColorOfButtonDemo()">
範例
以下是程式碼 −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
<label>
UserName:
</label>
<input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px"
onkeyup="changeTheColorOfButtonDemo()">
<br><br>
<button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>
</body>
<script>
function changeTheColorOfButtonDemo() {
if (document.getElementById("changeColorDemo").value !== "") {
document.getElementById("buttonDemo").style.background = "green";
} else {
document.getElementById("buttonDemo").style.background = "skyblue";
}
}
</script>
</html>要執行上述程式,請儲存檔名“anyName.html(index.html)”。右鍵單擊檔案,然後在 Visual Studio Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
這將在控制檯中產生以下輸出 −

當你在文字框中輸入內容時,按鈕的顏色會從天藍色變為綠色,如下所示 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP