簡體   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