问题
The idea was to put a tooltip with value related to slider. I thought initially to accomplish that task by using css grid
. CSS provides you with grid of any size, 10 or 1000 cols, doesn't matter. By utilizing grid functionality, we can align out tooltip as we wish.
What we really get is:
Thumb position is sort of unpredictable. It seems that it is being offset, and the direction of that offset is dependent on whether input value is in the left or right part of slider.
Note: default thumb behaves exactly the same way. I mean, shape of thumb is not of concern.
So, how does html calculate position of thumb based on its value?
回答1:
You have to take into consideration the size of your thumb
It is possible to achieve this using a little bit of javascript (unless you can get the range ratio which I am not aware of as of now)
Therorical
Calculate the ratio
of your current value
relative to the min
and max
of your input (between 0 and 1)
(value - el.min) / (el.max - el.min)
So its position (starting from the arrow relative to the input container) would be:
thumbSize / 2 + ratio * 100% - ration * thumbSize
Method
This might give an idea of how to implement this in 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)`
}
This above code has not been tested but the same method has been implemented
回答2:
For anyone else stumbling upon this problem, the issue is that the first and last position of thumb are offset by half the width of thumb
. Because of this, all of the other positions are slightly offset to compensate for the first and last one.
One simple solution for this is to normalize the thumb position between actual first and last thumb positions which are actually 0 + halfThumb
and width - halfThumb
respectively.
To normalize, we can use the formula recommended in this answer.
So the left
offset of absolutely positioned element in px
would be:
const left = (((value - minValue) / (valueMax - valueMin)) * ((totalInputWidth - thumbHalfWidth) - thumbHalfWidth)) + thumbHalfWidth;
Where
value
is actual input value.
minValue
is actual minimum value for input.
maxValue
is actual maximum value for input.
thumbHalfWidth
is half of the width of thumb used for slider drag.
totalInputWidth
is width of input element in pixels.
来源:https://stackoverflow.com/questions/48880523/how-to-precisely-find-thumb-position-of-input-type-range