本文实例为大家分享了Javascript实现拖动校验的具体代码,供大家参考,具体内容如下
思路
1、页面布局采用定位,背景颜色变化bg的宽度为0,其宽度会随着滑块的移动而移动。
页面结构
请滑动滑块
页面布局
.box {
width: 250px;
height: 50px;
background-color: #ccc;
position: relative;
margin: 0 auto;
}
.btn {
box-sizing: border-box;
width: 50px;
height: 50px;
border: 1px solid #ccc;
color: #ccc;
background-color: #fff;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
z-index: 4;
}
.text {
position: absolute;
height: 50px;
left: 50%;
transform: translateX(-50%);
z-index: 2;
user-select: none;
}
.bg {
width: 0;
height: 50px;
background-color: #25c20f;
z-index: 3;
position: absolute;
top: 0;
left: 0;
}
2、分析事件—鼠标按下,鼠标移动,鼠标松开
2.1 鼠标按下,获取此时事件的水平距离downX;鼠标移动,获取此时事件的水平距离e.clientX;那么鼠标移动的距离moveX = e.clientX - downX,也就是滑块跟着移动的距离。即btn.style.left = moveX + 'px';同时bg的宽度也就是滑块移动的距离,即bg.style.width = moveX + 'px'
2.2 滑块拉到头了,表示验证成功
什么时候表示滑块滑到头了,也就是moveX等于box的宽度-滑块的宽度。那么文字的改变成“验证成功”。且滑块停留在了最有端。无论鼠标点击还是移动,都不会在影响了。那就是清除事件,清除按钮的鼠标移动和鼠标按下事件btn.onmousemove = null; btn.onmousedown = null;//清除事件
此时验证成功,设立一个标记为表示验证成功flag=true,后续需要用到。
2.3 那么如果我们滑块拉到一半就松开了鼠标,滑块应该回到原始位置。但是如果已经验证成功了,那就不会回到原点。
鼠标松开事件触发,那么鼠标移动已经不能影响滑块了,那么此时需要清除移动事件btn.onmousemove = null;没有验证成功那就回到原点this.style.left = 0; bg.style.width = 0;
页面动作
function selector(name) {
return document.querySelector(name);
}
var box = selector('.box'),
btn = selector('.btn'),
text = selector('.text'),
bg = selector('.bg'),
flag = false;
// 鼠标按下,移动,松开
// 按下的距离和移动的距离差就是滑块移动的距离
btn.onmousedown = function (e) {//按钮按下的
var downX = e.clientX
btn.onmousemove = function(e){//e 事件的状态
var moveX = e.clientX - downX;
if(moveX > 0) {
this.style.left = moveX + 'px';
bg.style.width = moveX + 'px'
// 滑块拉到头了,表示验证成功
if (moveX >= box.offsetWidth - this.offsetWidth) {
bg.style.zIndex = 1;// 设置bg的z-index的值是为了处理党滑块经过原始值的时候,bg将文字覆盖了。验证成功后,有让文字显示出来
text.innerText = '验证成功';
text.style.color = '#fff';
flag = true;
// 此时鼠标移动或者按下,滑块不在跟着移动了
btn.onmousemove = null;//
btn.onmousedown = null;//清除事件
}
}
}
}
btn.onmouseup = function () {
btn.onmousemove = null;
// 如果验证成功了,那就不会回到原点
if(flag){
return ;
}
this.style.left = 0;
bg.style.width = 0;
}
完整可以运行的源码
Title .box { width: 250px; height: 50px; background-color: #ccc; position: relative; margin: 0 auto; } .btn { box-sizing: border-box; width: 50px; height: 50px; border: 1px solid #ccc; color: #ccc; background-color: #fff; position: absolute; left: 0; top: 0; cursor: pointer; z-index: 4; } .text { position: absolute; height: 50px; left: 50%; transform: translateX(-50%); z-index: 2; user-select: none; } .bg { width: 0; height: 50px; background-color: #25c20f; z-index: 3; position: absolute; top: 0; left: 0; } 请滑动滑块
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



