本文執行個體為大家分享了JavaScript實作滑塊驗證解鎖的具體代碼,供大家參考,具體内容如下
// 引入矢量圖示庫
Document
* {
margin: 0;
padding: 0;
}
.box {
width: 300px;
height: 40px;
line-height: 40px;
text-align: center;
background-color: #e8e8e8;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
position: relative;
margin-top: 100px;
margin-left: 200px;
}
.box .bgColor {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
}
.box .tips {
position: absolute;
width: 100%;
height: 40px;
line-height: 40px;
font-size: 14px;
color: #000;
text-align: center;
user-select: none;
}
.ball {
width: 50px;
height: 38px;
border: 1px solid #ccc;
background: #fff;
text-align: center;
cursor: move;
position: absolute;
top: 0;
left: 0;
}
滑動驗證
var box = document.getElementsByClassName("box")[0];
var ball = document.getElementsByClassName("ball")[0];
var bgColor = document.getElementsByClassName("bgColor")[0];
var tips = document.getElementsByClassName("tips")[0];
// 設定成功狀态
var isSuccess = false; //預設為false 不成功
ball.onmousedown = function(e) {
var e = e || window.event;
// 擷取滑鼠相對于事件源左上角的位置
var posx = e.offsetX;
// 每次滑鼠按下時 清除動畫樣式
ball.style.transition = "";
bgColor.style.transition = "";
document.onmousemove = function(e) {
var e = e || window.event;
var x = e.pageX - box.offsetLeft - posx;
var max = box.clientWidth - ball.clientWidth;
if (x <= 0) {
x = 0;
}
if (x >= max) {
x = max;
}
bgColor.style.width = x + "px";
ball.style.left = x + "px";
bgColor.style.backgroundColor = "#6ff";
if (x == max) {
success();
}
}
document.onmouseup = function() {
// 如果沒有解鎖成功則傳回原點
if (!isSuccess) {
bgColor.style.width = 0 + "px";
ball.style.left = 0 + "px";
ball.style.transition = "left 0.6s linear";
bgColor.style.transition = "width 0.6s linear";
}
// 滑鼠擡起時,移除滑鼠移動事件和滑鼠擡起事件
document.onmouseup = null;
document.onmousemove = null;
}
}
// 定義一個滑塊解鎖成功的方法
function success() {
isSuccess = true;
// 擷取圖示
var icon = ball.firstElementChild;
tips.textContent = "解鎖成功";
bgColor.style.backgroundColor = "lightgreen";
icon.className = "iconfont icon-gou";
icon.style.color = "lightgreen";
//滑動成功時,移除滑鼠按下事件
ball.onmousedown = null;
}
效果圖如下:
以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。