如何在输入字段填满时更改按钮的颜色 - JavaScript?
javascriptweb developmentfront end technologyobject oriented programming
假设以下是我们的按钮减号
<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 打开"选项。
输出
将在控制台上产生以下输出 −
当您在文本框中写入内容时,按钮的颜色将从天蓝色变为绿色,如下所示 −