HTML
<div id="selest">
<div id="lineDiv" class="lineDiv">
<div id="vals" class="vals">0</div>
<div id="minDiv" class="minDiv"></div>
</div>
</div>
css
/*滑塊樣式---------------------*/
.lineDiv {
position: relative;
height: 200px;
background: url(../../images/assessment/okbgS.png) no-repeat center;
width: 3px;
top: 6.5rem;
left: 10.6rem;
}
.lineDiv .minDiv {
position: absolute;
top: 200px;
left: -1.42rem;
width: 3rem;
height: 2rem;
text-align: center;
background: url(../../images/assessment/btnUpH.png) no-repeat top center;
background-size: 40%;
cursor: pointer;
}
.lineDiv .vals {
position: absolute;
top: -1.2rem;
left: -1.2rem;
width: 2.5rem;
height: 1rem;
line-height: 1rem;
font-size: 0.6rem;
text-align: center;
background: url(../../images/assessment/cmXs.png) no-repeat center;
background-size: 100%;
color: #fff;
}
JS
var lineDiv = document.getElementById('lineDiv'); //長線條
var minDiv = document.getElementById('minDiv'); //小方塊
var vals = document.getElementById("vals");
var ifBool = false; //判斷鼠標是否按下
//事件
var start = function(e) {
e.stopPropagation();
ifBool = true;
}
var move = function(e) {
if(ifBool) {
if(!e.touches) { //移動端
var x = e.clientY;
} else { //PC端
var x = e.touches[0].pageY;
}
var lineDiv_top = getPosition(lineDiv).top; //長線條的橫坐標
var minDiv_top = x - lineDiv_top; //小方塊相對于父元素(長線條)的top值
if(minDiv_top >= lineDiv.offsetHeight) {
minDiv_top = lineDiv.offsetHeight;
}
if(minDiv_top < 0) {
minDiv_top = 0;
}
//設(shè)置拖動后小方塊的Top值
minDiv.style.top = minDiv_top + "px";
var sume = (滑塊最大值-滑塊最小值)/步長;
if(sume>=0){
console.log(minDiv_top);
vals.innerText = parseInt((滑塊最大值/步長)-(minDiv_top* sume/滑塊長度 ))*步長;
}
}
}
var end = function(e) {
ifBool = false;
}
//鼠標按下方塊
minDiv.addEventListener("touchstart", start);
minDiv.addEventListener("mousedown", start);
//拖動
window.addEventListener("touchmove", move);
window.addEventListener("mousemove", move);
//鼠標松開
window.addEventListener("touchend", end);
window.addEventListener("mouseup", end);
//獲取元素的絕對位置
function getPosition(node) {
var top = node.offsetTop;
current = node.offsetParent;
while(current != null) {
top += current.offsetTop;
current = current.offsetParent;
}
return {
"top": top
};
}
//滑塊-----------------------------------------------------------------