繁体   English   中英

如何使用事件侦听器实时从两个输入框中获取值并将其存储在原始 JS 中的变量中?

[英]How to grab values from two input boxes in real time with event listener and store in variables in raw JS?

我正在尝试学习 JS,我正在给自己一个小项目。

基本上,该项目将是一个实时更改背景的输入框。 它将有两个选项,单色和渐变。

单色 state 将有一个输入框和一个切换到渐变模式的按钮。

渐变模式有两个输入框(用于渐变颜色)。

但是,我有一行代码将运行 function 每次将文本输入到输入框中以添加添加到变量的文本。 但问题是,由于我必须跟踪两个输入框,我似乎无法合并渐变模式的两个值,因为它们位于单独的 eventListeners 中。

有谁知道我怎么能做到这一点?

我在 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


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

    @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>```

我不确定您的目的是什么,只需添加:

inputs = document.querySelectorAll('input');

inputs[0].addEventListener('keyDown', ()=>{
console.log(inputs[0].value)
})

inputs[1].addEventListener('keyDown', ()=>{
console.log(inputs[1].value)
})

在您编写时立即返回值,只需将它们存储在全局 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;
})

我认为钩子事件: cut/pastepropertychange (对于 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>`;

不要为此使用按钮并手动维护 state,请使用为您执行此操作的元素,例如单选按钮。 也可以将其调整为复选框。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM