【问题标题】:Range slider with variable max value具有可变最大值的范围滑块
【发布时间】:2020-10-08 14:24:28
【问题描述】:

我有一个可以设置可变最大值的范围滑块。 40, 60, 80, 200 等。我是 Javascript,根据滑块值将滑块元素的背景设置为某种颜色。

const slider = document.getElementById('myRange')
slider.addEventListener('input', function () {  
  const sliderValue = slider.value
  const color = 'linear-gradient(to right, #2B73CC ' + sliderValue + '%, #fff 0%)'
  slider.style.background = color
}

这仅在最大值设置为 100 时有效。因为我使用 slider.value 作为 % 来设置滑块背景的样式。

如何更改sliderValue 的值以反映实际值为%

示例:范围滑块的最大值设置为 40。当用户滚动到滑块末尾时,该值为 40。现在它将40% 传递到我的背景,填充滑块条为 40%。

如果slider.value 等于范围滑块上设置的最大值,我需要一些方法将sliderValue 设置为100%。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以将value 除以max 并乘以100

    const onSliderChange = (e) => {
      const
        slider         = e.target,
        container      = slider.parentElement,
        { value, max } = slider,
        percentage     = value / max * 100,
        color          = `linear-gradient(to right, #2B73CC ${percentage}%, #fff 0%)`;
      container.style.background = color;
    };
    
    const
      sliderContainer = document.querySelector('.slider-container'),
      slider          = sliderContainer.querySelector('.slider');
    
    slider.addEventListener('input', onSliderChange);
    .slider-container .slider {
      width: 100%;
    }
    <div class="slider-container">
      <input type="range" min="1" max="40" value="10" class="slider">
    </div>

    【讨论】:

    • 有趣,只是有点不同,但结果是一样的:)
    【解决方案2】:

    想了想解决这个问题所需要的全部精力。数学不是我的强项。但是:

    console.log(sliderValue / (this.sliderValues.max / 100)) 应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多