繁体   English   中英

如何使用javascript将输入集中在范围滑块上?

[英]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.

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