javascript - Javascript:非线性范围滑块
问题描述
我已经构建了这个范围滑块,但想让它的行为有所不同。我想知道是否可以使滑块手柄的值在到达滑块中心时为 1,000,而在右端时应为 10,000。
以下是我到目前为止的代码:
$('input[type="range"]').rangeslider({
polyfill: false,
onSlide: function (pos, val) {
$('input[type="text"]').val(val)
},
onSlideEnd: function(position, value) {
const sliderValue = value;
if (value >= 1000) {
const upperLimit = Math.ceil(value/100) * 100
const lowerLimit = Math.floor(value/100) * 100
const upperWeight = Math.abs( upperLimit - value)
const lowerWeight = Math.abs( value - lowerLimit)
value = upperLimit
if (upperWeight > lowerWeight) {
value = lowerLimit
}
}
if (value >= 10000) {
value = 10000
}
$('input[type="range"]').val(value).change()
},
});
$('input[type="text"]').on('blur', function (e) {
$('input[type="range"]').val($(this).val()).change()
})
.container {
width: 80%;
margin: 10px auto;
}
input[type="text"] {
margin-top: 50px;
display: block;
width: 100%;
height: 60px;
border: 1px solid #EBEBEB;
border-radius: 5px;
font-size: 25px;
color: #444;
padding: 5px 25px;
outline: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.2/rangeslider.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.2/rangeslider.js"></script>
<div class="container">
<input
type="range"
min="100"
max="10000"
step="10"
value="1000"
/>
<input type="text"/>
</div>
下图显示了我想要实现的目标。
解决方案
您只需在x 轴(从 0 到 100)上找到一个指数函数,它在y 轴(从 100 到 10000)上具有所需的输出。
然后,您调整您input
的x值,并在使用输出的任何地方计算y 。
const x = document.getElementById('input');
const y = document.getElementById('output');
const a = 100;
const b = Math.pow(a, 1/a);
function updateOutput(event) {
y.innerText = Math.floor(a * Math.pow(b, x.value));
}
updateOutput();
input.addEventListener('mousemove', updateOutput);
<input
id="input"
type="range"
min="0"
max="100"
value="0"
step="1"
/>
<div id="output"></div>
推荐阅读
- java - InputStream & OutputStream 抛出空指针异常?
- r - 在零元素处拆分向量
- angularjs - Woocommerce wp rest api“缺少 OAuth 参数 oauth_consumer_key”错误和“无效签名 - 提供的签名不匹配”。
- java - 单击以打开新菜单时为工厂设置动画
- android - 以接口为参数的 Dagger
- django - Heroku 不显示我最新的 django 模板更改
- scala - 如何在集合类型之间转换 - 在 Scala 中设置为 ListSet
- javascript - 显示存储在常量内的变量中的图像
- sql - 通过python发送SQL
- javafx - JavaFX 如何使节点始终在前面并完全可见?