js拖拽验证

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;

}

#d1 {
width: 300px;
height: 40px;
border: 1px solid #ccc;
margin-left: 300px;
margin-top: 100px;
position: relative;
display: flex;
flex-direction: row;
flex: 1;
cursor: pointer;

}

#d3 {
flex: 0;
background: #58bc58;
float: left;

}

#d4 {
flex: 1;
float: left;
}

#d2 {
flex: 1;
height: 40px;
width: 40px;
background: orangered;
position: absolute;
top: 0;
left: 0;
float: left;
box-sizing: border-box;
padding: 10px;
cursor: pointer;
user-select: none;
}

#but {
width: 80px;
height: 40px;
position: absolute;
left: 603px;
top: 100px;
cursor: pointer;
font-size: 16px;
}
</style>
<script>
window.onload = function () {
//获取节点
var d1 = document.getElementById("d1");
var d2 = document.getElementById("d2");

//鼠标按下事件
d2.onmousedown = function (ev) {
var ix = ev.offsetX;//获取水平偏移量
document.onmousemove = function (ev) {
var l = ev.clientX - ix - d1.offsetLeft;//水平移动的距离
// console.log(ev.clientX);
if (l <= 0) {//边界限制
l = 0;
d2.style.background = "orangered";//滑块颜色

} else if (l > (d1.offsetWidth - d2.offsetWidth)) {//限制最远距离
l = d1.offsetWidth - d2.offsetWidth;
d2.style.background = "green";////滑块颜色
d2.innerHTML = "✔";
// d3.style.display = "block";
}
var x = l / d1.offsetWidth;
d3.style.flex = (x + 0.05);
d4.style.flex = (1 - x);
// if (l = d1.offsetWidth - d2.offsetWidth) {
// d3.style.flex = 1;
// }
d2.style.left = l + "px";//设置左移位置
// d3.style.left = l + "px";
// d1.style.background = "orange";
ev.stopPropagation();
}
document.onmouseup = function (ev) {//鼠标松开
document.onmousemove = null;
var l = d2.offsetLeft//水平移动的距离
if (l == d1.offsetWidth - d2.offsetWidth) {
d2.style.left = (d1.offsetWidth - d2.offsetWidth) + "px";
d2.style.background = "green";////滑块颜色
d2.innerHTML = "✔";
d3.style.flex = 1;
d3.style.background = "#58bc58";
d4.style.flex = 0;
// console.log(l);
} else {
d2.style.left = 0;
d2.innerHTML = "→";
d3.style.flex = 0;
d4.style.flex = 1;
}
// ev.stopPropagation();
}

}
but.onclick = function () {
d2.style.left = 0;
d2.innerHTML = "→";
d3.style.flex = 0;
d4.style.flex = 1;
d2.style.background = "orangered";

}

}
</script>

</head>

<body>
<div id="d1">
<div id="d3"></div>

<div id="d2"> → </div>
<div id="d4"></div>

</div>
<input type="button" value="重置" id="but">

</body>

</html>

猜你喜欢

转载自www.cnblogs.com/sun-shine1229/p/10702114.html