gpt4 book ai didi

javascript - 确定范围输入上 "thumb"的移动范围

转载 作者:行者123 更新时间:2023-12-03 09:55:53 27 4
gpt4 key购买 nike

我正在尝试显示位于拇指上方居中的范围项的值。通过读取值并将元素定位在范围元素上方作为其 clientWidth 的百分比,这非常有效。

然而,距离中间的偏移量越来越大(见图片),这导致值不在拇指上居中。我确信这是因为拇指实际移动小于 clientWidth,因为拇指本身的大小和轨道周围可能有一些空间。

我该如何考虑这一点?

Correct positioning in the center

Offset to the left

And to the right

JSFiddle 可以在这里找到:https://jsfiddle.net/jd4kncuk/

var myRange = document.querySelector('#myRange');
var myValue = document.querySelector('#myValue');

var off = myRange.clientWidth / (parseInt(myRange.max) - parseInt(myRange.min));
var px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.clientWidth / 2);

myValue.style.left = px + 'px';
myValue.style.top = -myRange.offsetHeight - 5 + 'px';
myValue.innerHTML = myRange.value;

myRange.oninput = function() {
let px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.clientWidth / 2);
myValue.innerHTML = myRange.value;
myValue.style.left = px + 'px';
};
<div style="position:relative; margin:auto; width:90%; margin-top:80px;">
<output style="position:absolute; min-width:100px; text-align: center;" id="myValue"></output>
<input type="range" id="myRange" min="0" max="200" step="5" style="width:80%" value="80">
</div>

最佳答案

查看更多使用 CSS 的信息: link

var myRange = document.querySelector('#myRange');
var myValue = document.querySelector('#myValue');
var thumbWidth = 18;

var off = (myRange.clientWidth - thumbWidth) / (parseInt(myRange.max) - parseInt(myRange.min));
var px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.clientWidth / 2) + (thumbWidth / 2);

myValue.style.left = px + 'px';
myValue.style.top = -myRange.offsetHeight - 5 + 'px';
myValue.innerHTML = myRange.value;

myRange.oninput = function() {
let px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.clientWidth / 2) + (thumbWidth / 2);
myValue.innerHTML = myRange.value;
myValue.style.left = px + 'px';
};
<div style="position:relative; margin:auto; width:90%; margin-top:80px;">
<output style="position:absolute; min-width:100px; text-align: center;" id="myValue"></output>
<input type="range" id="myRange" min="0" max="200" step="5" style="width:80%" value="80">
</div>

关于javascript - 确定范围输入上 "thumb"的移动范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41549817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com