首页 > 解决方案 > 如何使用 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;}

有没有办法让输入焦点/不关注范围滑块的使用?

标签: javascriptformsinputrangeslider

解决方案


不,您不能,因为这只会将光标移到输入字段中,并且滑块会失去焦点,即焦点是,您不能同时关注两个项目:

例子:

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>


推荐阅读