gpt4 book ai didi

javascript - 如何: Change color of button when an input is given to a textbox

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:37 24 4
gpt4 key购买 nike

刚刚学习 JS 并卡在这里。

我有一个文本框和一个按钮。每当有人在文本框中提供值时,我希望按钮的颜色发生变化(比如红色)。当文本框保持为空时,按钮的颜色保持其初始颜色状态。

这是我写的代码::

HTML::

    var text1 = document.getElementById("input1");
var butt1 = document.getElementById("button1");

if (text1.value == null || text1.value == "") {
butt1.style.backgroundColor = "white";
}
else {
butt1.style.backgroundColor = "#F22613";
}
    #button1 {
height: 20px;
width: 100px;
}
<input type="text" id="input1" value="xyz">
<button type="submit" id="button1">

最佳答案

您需要将事件监听器附加到 textBox 上的事件 keyup

var text1 = document.getElementById("input1");
var butt1 = document.getElementById("button1");

text1.addEventListener('keyup', function(){

if (text1.value == null || text1.value == "") {
butt1.style.backgroundColor = "white";
}
else {
butt1.style.backgroundColor = "#F22613";
}
});
#button1 {
height: 20px;
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="input1" value="xyz">
<button type="submit" id="button1" >
</body>
</html>

关于javascript - 如何: Change color of button when an input is given to a textbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40459951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com