如何使用 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;}

有什么方法可以在使用范围滑块时输入 focus/unfocus 吗?

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

示例:

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>

编辑:

如果你的输入计算是由焦点控制的(顺便说一句,他们可以做到 on-change,根据我的理解, 会更好),你可以设置单独的事件在滑块中向上移动鼠标将触发对您的输入的关注;

虽然你在使用滑块时焦点当然在滑块上,但是一旦你松开它,你可以s输入:

示例:

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>

另外,从您的其他 link 评论中,我看到您使用的 onfocusout 事件很难触发,所以我建议使用 blur:

(但如果你只是简单地使用 on change,所有这些似乎都是多余的...)

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>