我是Java的新手,正尝试自己创建Jquery UI自定义范围滑块。以下是此任务的html和css代码。
#slider {
position: relative;
height: 15px;
width: 400px;
margin: 10px;
border: 1px solid #c5c5c5;
}
.ui-slider {
position: absolute;
width: 20px;
height: 20px;
background-color: rgb(246, 246, 246);
border: 1px solid #c5c5c5;
left: 50%;
top: -4.5px;
border-radius: 3px;
}
.ui-slider:hover {
background-color: rgb(237, 237, 237);
}
<div id="slider">
<span class="ui-slider"></span>
</div>
现在,我认为应该将一些JavaScript事件附加到span
元素上,以使其来回滑动。我应该为这个任务使用mouseDown
还是onDrag
事件监听器?请帮助我编写JavaScript代码,以使此滑块实际工作。您可以找到我想在this link上构建的滑块。
答案 0 :(得分:1)
var sliderSpan = document.getElementById("slider-span");
var slider = document.getElementById("slider");
sliderSpan.onmousedown = function(event) {
var sliderCoords = getCoords(slider);
var sliderSpanCoords = getCoords(sliderSpan);
var shift = event.pageX - sliderSpanCoords.left;
document.onmousemove = function(event) {
var left =
((event.pageX - shift - sliderCoords.left) / sliderCoords.width) * 100;
if (left < 0) left = 0;
if (left > 100) left = 100;
sliderSpan.style.left = left + "%";
};
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
};
return false;
};
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset,
width: box.right - box.left
};
}
#slider {
position: relative;
height: 15px;
width: 400px;
margin: 10px;
border: 1px solid #c5c5c5;
}
.ui-slider {
position: absolute;
width: 20px;
height: 20px;
background-color: rgb(246, 246, 246);
border: 1px solid #c5c5c5;
left: 0%;
top: -4.5px;
border-radius: 3px;
margin-left: -10px;
}
.ui-slider:hover {
background-color: rgb(237, 237, 237);
}
<div id="slider">
<span class="ui-slider" id="slider-span"></span>
</div>
答案 1 :(得分:0)
不确定是否需要javascript,
尝试一下:
<input type="range" min="0" max="5" step="0.5" value="2.5" />