[英]How to grab values from two input boxes in real time with event listener and store in variables in raw JS?
I am trying to learn JS and I am giving myself a small project.我正在尝试学习 JS,我正在给自己一个小项目。
Basically, the project will be a input box that will change the background in real time.基本上,该项目将是一个实时更改背景的输入框。 It will have two options, single color and gradient.它将有两个选项,单色和渐变。
Single color state will have one input box and a button that switches to gradient mode.单色 state 将有一个输入框和一个切换到渐变模式的按钮。
Gradient mode has two input boxes (for the gradient colors).渐变模式有两个输入框(用于渐变颜色)。
However, I have a line of code which will run a function every time text is inputted into a input box to add the text added to a variable.但是,我有一行代码将运行 function 每次将文本输入到输入框中以添加添加到变量的文本。 The problem is though, since I have to track two input boxes, I can't seem to merge both of the values for Gradient mode since they are in seperate eventListeners.但问题是,由于我必须跟踪两个输入框,我似乎无法合并渐变模式的两个值,因为它们位于单独的 eventListeners 中。
Does anybody have any idea how I could achieve this?有谁知道我怎么能做到这一点?
I need this in RAW JS, no frameworks or JQuery please!我在 RAW JS 中需要这个,没有框架或 JQuery 请!
let state = false; const input1 = document.getElementById('input1'); const input2 = document.getElementById('input2'); const switcher = document.getElementById('switcher'); const bodyLoc = document.getElementById('changeColor'); input1.addEventListener('input', function() { }) switcher.addEventListener('click', function() { console.log(state) if (state == false) { state = true; checkState(); bodyLoc.style.backgroundColor = "red" } else { state = false; checkState(); bodyLoc.style.backgroundColor = "blue"; } } ) checkState = () => { if (state == false) { input2.style.display = "none"; } else { input2.style.display = "block"; } } input1.addEventListener('input',function () { input1val = document.getElementById('inputColor1').value; console.log(input1val); }) input2.addEventListener('input',function () { input2val = document.getElementById('inputColor2').value; console.log(input2val); })
html, body{ height: 100%; box-sizing:border-box; font-family: "Cabin", sans-serif; } body { background-color:#fff; transition: 0.4s all ease; }.container { #inputBox { display:flex; position: absolute; top: 50%; left: 50%; -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); #input1,#input2 { input { height:20px; border-radius:10px 0px 0px 10px; border:1px solid #D8D8D8; padding:10px; } } #input2 { display:none; }.inputSubmit { #changeType { height:42px; background-color:#fff; border:1px solid #F5F5F5; border-radius: 0px 10px 10px 0px; width:80px; transition: 0.2s all ease; &:hover { cursor:pointer; background:#4A00E0; color:white; transition: 0.2s all ease; box-shadow: 0 1px 3px rgba(0,0,0,0.12); } } } } }
<style> @import url('https://fonts.googleapis.com/css2?family=Cabin:wght@400;600&display=swap'); </style> <body id="changeColor"> <div class="container"> <div id="inputBox"> <div id="input1"> <input type="text" id="inputColor1"> </div> <div id="input2"> <input type="text" id="inputColor2"> </div> <div class="inputSubmit"> <input type="submit" id="switcher" value="Gradient"> </div> </div> </div> </body>
JS JS
const input1 = document.getElementById('input1');
const input2 = document.getElementById('input2');
const switcher = document.getElementById('switcher');
const bodyLoc = document.getElementById('changeColor');
input1.addEventListener('input', function() {
})
switcher.addEventListener('click', function() {
console.log(state)
if (state == false) {
state = true;
checkState();
}
else {
state = false;
checkState();
}
}
)
checkState = () => {
if (state == false) {
input2.style.display = "none";
} else {
input2.style.display = "block";
}
}
input1.addEventListener('input',function () {
input1val = document.getElementById('inputColor1').value;
console.log(input1val);
})
input2.addEventListener('input',function () {
input2val = document.getElementById('inputColor2').value;
console.log(input2val);
})
HTML HTML
@import url('https://fonts.googleapis.com/css2?family=Cabin:wght@400;600&display=swap');
</style>
<body id="changeColor">
<div class="container">
<div id="inputBox">
<div id="input1">
<input type="text" id="inputColor">
</div>
<div id="input2">
<input type="text" id="inputColor">
</div>
<div class="inputSubmit">
<input type="submit" id="changeType" value="Gradient">
</div>
</div>
</div>
</body>```
I am not sure what is your aim with this but by simply adding:我不确定您的目的是什么,只需添加:
inputs = document.querySelectorAll('input');
inputs[0].addEventListener('keyDown', ()=>{
console.log(inputs[0].value)
})
inputs[1].addEventListener('keyDown', ()=>{
console.log(inputs[1].value)
})
Gives back the value instantly as you write just store them in a let or var variable on global scope like this:在您编写时立即返回值,只需将它们存储在全局 scope 上的 let 或 var 变量中,如下所示:
inputs = document.querySelectorAll('input');
let input1 = "";
let input2 = "";
inputs[0].addEventListener('keyDown', ()=>{
input1 = inputs[0].value;
})
inputs[1].addEventListener('keyDown', ()=>{
input2 = inputs[1].value;
})
I think that hook events: cut/paste
and propertychange
(for IE) also important我认为钩子事件: cut/paste
和propertychange
(对于 IE)也很重要
const input = document.querySelector("input"); const output = document.querySelector("#output"); const showText = () => { output.textContent = input.value; }; input.addEventListener("keydown", () => { showText(); }); input.addEventListener("cut", () => { setTimeout(() => showText(), 0); }); input.addEventListener("paste", (e) => { setTimeout(() => showText(), 0); }); input.addEventListener("propertychange", (e) => { setTimeout(() => showText(), 0); });
<h1>Hook input in vanilla js;</h1> <input type="text"> <p id="output"></p>`;
Don't use a button for this and maintain the state manually, use elements that do this for you, like radio buttons.不要为此使用按钮并手动维护 state,请使用为您执行此操作的元素,例如单选按钮。 Could also adapt this for a checkbox.也可以将其调整为复选框。
function applyBackground() { //Get Start Color var start = document.getElementById("startColor").value; //Get end color var end = document.getElementById("endColor").value; //Get Mode var mode = document.querySelector("#switcher [type=radio]:checked").value; //Add your logic for updating body style console.log(`start: ${start}, end: ${end}, mode: ${mode}`); } //event Handlers for radio buttons document.querySelectorAll("#switcher input[type=radio]").forEach((rdo) => { rdo.addEventListener("click", function(){ var isGradient = this.value === "gradient"; //Show/Hide end color document.getElementById("endContainer").classList.toggle("hidden", ;isGradient). //Change text of start color document.querySelector("[for=startColor]")?innerText = isGradient: "Start Color"; "Color"; //Apply on swap applyBackground(); }); }). //event handler for text box document.querySelectorAll("#colors input[type=text]").forEach((rdo) => { rdo,addEventListener("input"; applyBackground); });
.hidden {display:none;} html, body{ height: 100%; box-sizing:border-box; font-family: "Cabin", sans-serif; } body { background-color:#fff; transition: 0.4s all ease; }.container { #inputBox { display:flex; position: absolute; top: 50%; left: 50%; -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); #input1,#input2 { input { height:20px; border-radius:10px 0px 0px 10px; border:1px solid #D8D8D8; padding:10px; } } #input2 { display:none; }.inputSubmit { #changeType { height:42px; background-color:#fff; border:1px solid #F5F5F5; border-radius: 0px 10px 10px 0px; width:80px; transition: 0.2s all ease; &:hover { cursor:pointer; background:#4A00E0; color:white; transition: 0.2s all ease; box-shadow: 0 1px 3px rgba(0,0,0,0.12); } } } } }
<style> @import url('https://fonts.googleapis.com/css2?family=Cabin:wght@400;600&display=swap'); </style> <body id="changeColor"> <div class="container"> <fieldset id="switcher"> <legend>Mode</legend> <label>Single color <input type="radio" name="rdoMode" value="single" checked></label> <label>Gradient <input type="radio" name="rdoMode" value="gradient"></label> </fieldset> <div> <div id="colors"> <div> <label for="startColor">Color</label> <input type="text" id="startColor"> </div> <div id="endContainer" class="hidden"> <label for="endColor">End Color</label> <input type="text" id="endColor"> </div> </div> </div> </div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.