如何创建输入类型为“range”的科学 HTML 滑块

Bas*_*asj 11 html javascript css html-input

我需要创建一个科学输入滑块。更确切地说:

  • n 个刻度,例如:无论范围(0 - 200、1 - 11 等),我想要 11 个刻度覆盖整个范围
  • 每个刻度下方的数值标签
  • 当滑块光标靠近刻度线时,没有“粘合”吸引力效果

小样:

在此输入图像描述

笔记:

以下代码生成一个带有刻度的 HTML 滑块,并且它可以工作。然而,它不符合上述第二个和第三个标准。

input { width: 400px; }
Run Code Online (Sandbox Code Playgroud)
<input type=range min=0 max=200 value=0 step=1 list=tickmarks>
<datalist id=tickmarks>
    <option>0</option>
    <option>20</option>
    <option>40</option>
    <option>60</option>
    <option>80</option>
    <option>100</option>
    <option>120</option>
    <option>140</option>
    <option>160</option>
    <option>180</option>
    <option>200</option>
 </datalist>
Run Code Online (Sandbox Code Playgroud)

HTML 是否有一个属性<input type="range">可以启用这些“数字标签”刻度?

满足所有三个标准的实施是否可能?

jla*_*jla 5

正如 Lajos Arpad 的回答所示,最好避免使用,datalist因为您的要求超出了它的能力。您需要手动创建带有数值的刻度。

以下代码使用与问题中的原始代码类似的 HTML 布局,并具有适合的样式。请注意,宽度是在父元素上设置的,如果父元素太小,则刻度数将换行。为了解决这个问题,您可能需要减小刻度号字体大小。

为了让刻度在所有主要浏览器中正确排列,最好对滑块进行样式设置,使其在浏览器中看起来相同。包括针对范围滑块的 Chrome 和 Firefox 特定伪元素的样式。结果在所有基于 Chromium 和 Mozilla 的浏览器中看起来应该是相同的。

请注意,如问题所示,填充范围滑块的真正跨浏览器方法只能使用 JavaScript 来实现。这里的 JavaScript 基本上是从这个答案复制的

const input = document.querySelector("#input input")
input.addEventListener( 'input', function() {
    const value = (this.value-this.min)/(this.max-this.min)*100;
    this.style.background = 'linear-gradient(to right, #35b0f2 0%, #35b0f2 ' + value + '%, #ccc ' + value + '%, #ccc 100%)';
} );
Run Code Online (Sandbox Code Playgroud)
#input {
    width: 400px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
#input span {
    position: relative;
    margin: 15px -5px 0 -5px;
    flex-basis: 0;
    flex-grow: 1;
    text-align: center;
    font-size: 0.85em;
    user-select: none;
}
#input span::after {
    content: "";
    position: absolute;
    width: 1px;
    height: 8px;
    left: 0;
    right: 0;
    margin: auto;
    top: -12px;
    background-color: #ccc;
}
#input input {
    width: 100%;
    margin: 5px 10px;
    position: relative;
    background-color: #ccc;
    border-radius: 99px;
    z-index: 10;
    height: 7px;
    -webkit-appearance: none;
}
#input input::-moz-range-thumb {
    border: none;
    height: 16px;
    width: 16px;
    border-radius: 99px;
    background: #35b0f2;
    cursor: pointer;
}
#input input::-webkit-slider-thumb {
  box-shadow: none
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 99px;
  background-color: #35b0f2;
  cursor: pointer;
  -webkit-appearance: none;
}
Run Code Online (Sandbox Code Playgroud)
<div id="input">
    <input type=range min=0 max=200 value=0 step=1>
    <span>0</span>
    <span>20</span>
    <span>40</span>
    <span>60</span>
    <span>80</span>
    <span>100</span>
    <span>120</span>
    <span>140</span>
    <span>160</span>
    <span>180</span>
    <span>200</span>
</div>
Run Code Online (Sandbox Code Playgroud)