如何精确找到输入的拇指位置[type =“range”]?

问题描述 投票:1回答:1

我们的想法是提供一个与滑块相关的工具提示。我最初想通过使用css grid来完成这项任务。 CSS为您提供任意大小的网格,10或1000列,无关紧要。通过利用网格功能,我们可以根据需要调整工具提示。我们真正得到的是:

thumb is unstable

拇指位置有点不可预测。它似乎是偏移的,并且该偏移的方向取决于输入值是在滑块的左侧还是右侧。

注意:默认拇指的行为方式完全相同。我的意思是,拇指的形状并不重要。

那么,html如何根据其值计算拇指位置?

css slider range
1个回答
1
投票

你必须考虑你的thumb的大小

可以使用一点点javascript实现这一点(除非你能得到我现在不知道的范围比)

Therorical

计算当前ratio相对于输入的valueminmax(0到1之间)

(value - el.min) / (el.max - el.min)

所以它的位置(从相对于输入容器的箭头开始)将是:

thumbSize / 2 + ratio * 100% - ration * thumbSize

Method

这可能会让我们知道如何在javascript中实现它

const thumbSize = 10
const range = document.querySelector('input[type=range]')
const tooltip = document.querySelector('.tooltip')

range.addEventListener('input', e => {
  const ratio = (range.value - range.min) / (range.max - range.min)
  tooltip.style.left = `calc(${thumbSize / 10}px + ${ratio * 100} - ${ratio} * ${thumbSize}px)`
}

上面的代码尚未经过测试,但已实施相同的方法

© www.soinside.com 2019 - 2024. All rights reserved.