[英]How can I focus input on a range slider with javascript?
我有用戶輸入,可以直接在其中輸入值或使用范圍滑塊選擇它。 我想要的是,當用戶選擇范圍滑塊時,它會同時關注它控制的輸入。
所以我有這些輸入:
<label class="va1">Option a price 1:<input id="a1" type="number"/></label>
<input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
這個使范圍滑塊的值進入輸入的js:
var opt_1 = document.getElementById("slider-a1");
opt_1.oninput = function() {
document.getElementById("a1").value = opt_1.value;}
有什么方法可以使輸入聚焦/不聚焦於范圍滑塊的使用?
不,你不能,因為這只會將光標移到輸入字段中,滑塊將失去焦點,即焦點是,你不能同時關注兩個項目:
例子:
var opt_1 = document.getElementById("slider-a1"); opt_1.oninput = function() { document.getElementById("a1").value = opt_1.value; document.getElementById("a1").focus(); }
.active { border-color:red; border-style: inset; border-width: 1px;}
<label class="va1">Option a price 1:<input id="a1" type="number"/></label> <input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
所以我建議模仿焦點:
var opt_1 = document.getElementById("slider-a1"); opt_1.oninput = function() { document.getElementById("a1").value = opt_1.value; document.getElementById("a1").classList.add("active"); }
.active { border-color:blue; border-style: inset; border-width: 2px;}
<label class="va1">Option a price 1:<input id="a1" type="number"/></label> <input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
編輯:
如果您的輸入計算由焦點控制(順便說一句,他們可以隨時更改,根據我的理解,我認為女巫會更好),您可以設置單獨的事件,在滑塊中鼠標向上時將觸發對您輸入的關注;
當您使用滑塊時,當然焦點在滑塊上,但是一旦您釋放它,您就可以切換到輸入:
例子:
var opt_1 = document.getElementById("slider-a1"); opt_1.oninput = function() { document.getElementById("a1").value = opt_1.value; } opt_1.onmouseup = function() { document.getElementById("a1").focus(); }
<label class="va1">Option a price 1:<input id="a1" type="number"/></label> <input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
同樣從您評論中的其他鏈接我看到您正在使用 onfocusout 事件很難觸發,所以我建議使用模糊:
(但如果您只是簡單地使用更改,所有這些似乎都是多余的......)
var opt_1 = document.getElementById("slider-a1"); opt_1.oninput = function() { document.getElementById("a1").value = opt_1.value; } opt_1.onmouseup = function() { document.getElementById("a1").focus(); setTimeout(function() { console.log(true) opt_1.focus(); }, 1000); } document.getElementById("a1").onblur = function() { console.log("blur out happend") };
<label class="va1">Option a price 1:<input id="a1" type="number"/></label> <input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.