当值更改时,防止滑块跳跃

时间:2018-06-01 08:40:32

标签: javascript css

我有一个实时更新其右侧标签标签上的值的滑块。当值从1位数值变为2位数值时,我该怎么做才能防止它“跳跃”?如何为标签指定固定位置,以免改变布局:

var range = document.getElementById('range');
range.addEventListener('input', rangeChange);

function rangeChange() {
  label.innerHTML = this.value;
}
<label id="label">0</label>
<input id="range" type="range" value=0 min=0 max=100>

2 个答案:

答案 0 :(得分:2)

width: 20px;display: inline-block;添加到标签中。

在两个元素周围添加一个包装器,并为标签提供display: flex; align-items: center;样式和宽度。

&#13;
&#13;
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);

function rangeChange() {
  label.innerHTML = this.value;
}
&#13;
<div style="display: flex; align-items: center;">
<label id="label" style="width: 20px;">0</label>
<input id="range" type="range" value=0 min=0 max=100>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

选项1:将标签放在滑块的右侧

&#13;
&#13;
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);

function rangeChange() {
  label.innerHTML = this.value;
}
&#13;
<input id="range" type="range" value=0 min=0 max=100>
<label id="label">0</label>
&#13;
&#13;
&#13;

选项2:零填充:

&#13;
&#13;
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);

function rangeChange() {
  var val = +(this.value);
  if (10 > val) {
    val = '00' + val;
  } else if (100 > val) {
    val = '0' + val;
  }
  label.innerHTML = val;
}
&#13;
<label id="label">000</label>
<input id="range" type="range" value=0 min=0 max=100>
&#13;
&#13;
&#13;