<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 160px;
height: 20px;
border: 1px solid rgb(0, 0, 0);
position: relative;
text-align: center;
line-height: 20px;
font-size: 12px;
-webkit-user-select: none;
overflow: hidden;
}
.card{
height: 20px;
width: 20px;
position: absolute;
border-left: 1px solid;
border-right: 1px solid;
top: -0;
left: -1px;
cursor: pointer;
background-color: white;
}
.load{
height: 20px;
position: absolute;
border: 0;
top: 0;
background-color: beige;
}
</style>
</head>
<body>
<div class="box">
向右滑动完成验证
<div class="card" id="card">></div>
<div class="load"></div>
</div>
</body>
<script>
window.onload = function(){
const card = document.querySelectorAll('#card')[0] // 滑块
const box = document.querySelectorAll('.box')[0] // 容器
const load = document.querySelectorAll('.load')[0] // 滑动div
let x = 0
let movex = 0
card.addEventListener('mousedown',down) //添加鼠标按下事件
function down(e){
x = e.screenX //鼠标点击位置 X 坐标
card.addEventListener('mousemove',move) //添加鼠标移动事件
}
function move(e){
card.style.left = e.clientX - x + 'px' //鼠标移动距离 - 点击位置x坐标
load.style.width = e.clientX - x + 'px'
if(e.clientX - x >= box.clientWidth - card.clientWidth) { // 当滑块移动到容器最右端
movex = e.clientX - x
card.style.left = e.clientX - x // 滑块停在当前位置
card.removeEventListener('mousedown',down) // 移除事件
card.removeEventListener('mousemove',move)
load.innerHTML = '验证成功'
}
}
card.addEventListener('mouseup',function(e){ // 添加鼠标抬起事件
card.removeEventListener('mousedown',down) // 移除 按下事件
card.removeEventListener('mousemove',move) // 移除 移动事件
card.addEventListener('mousedown',down)
if(e.clientX - x < box.clientWidth - card.clientWidth){ // 没有滑到最右端 重置滑块位置
card.style.left = -1 + 'px'
load.style.width = 0 + 'px'
}
})
card.addEventListener('mouseout',function(e){ // 鼠标移到滑块外
if(card.style.left != (movex + 'px')){ // 滑块不在最右端 重置滑块位置和滑块事件
card.style.left = -1 + 'px'
load.style.width = 0 + 'px'
card.removeEventListener('mousedown',down)
card.removeEventListener('mousemove',move)
card.addEventListener('mousedown',down)
}
})
}
</script>
</html>