只是学习JS并坚持到这里。
我有一个文本框和一个按钮。每当有人在文本框中提供值时,我希望按钮的颜色更改(例如红色)。当文本框保持为null时,按钮的颜色将保持其初始颜色状态。
这是我写的代码::
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">
答案 0 :(得分:1)
您需要将事件监听器附加到keyup
上的事件textBox
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";
}
});
&#13;
#button1 {
height: 20px;
width: 100px;
}
&#13;
<!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>
&#13;
答案 1 :(得分:0)
我创建了oninput
函数,它将在您输入的时候验证
function input(){
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";
}
}
&#13;
#button1 {
height: 20px;
width: 100px;
}
&#13;
<input type="text" id="input1" value="xyz" oninput="input()">
<button type="submit" id="button1">
&#13;
答案 2 :(得分:0)
您需要将onChange
属性附加到文本框并为其指定一个函数。只要the value in the textbox is changed
,就会调用该函数。这是codepen link。
或者,您也可以在文本框中指定eventlistener of keyup
。您可以在此codepen link 2中找到该解决方案。
function myFunction(){
var text1 = document.getElementById("input1");
var butt1 = document.getElementById("button1");
if (text1.value == null || text1.value == "") {
butt1.style.backgroundColor = "white";
}
else {
butt1.style.backgroundColor = "red";
}
}
&#13;
#button1 {
height: 20px;
width: 100px;
}
&#13;
<input type="text" id="input1" value="xyz" onchange="myFunction()">
<button type="submit" id="button1">Something</button>
&#13;
答案 3 :(得分:0)
<html>
<head>
<title>Enter Press Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function(){
var text1 = document.getElementById("input1");
var butt1 = document.getElementById("button1");
text1.addEventListener('keyup', function(){
if (text1.value == null || text1.value == "") {
butt1.style.backgroundColor = "";
}
else {
butt1.style.backgroundColor = "#F22613";
}
});
};
</script>
</head>
<body>
<input type="text" id="input1" value="">
<button type="submit" id="button1">Submit</button>
</body>
</html>