1.前端頁面應用滑塊驗證可以防止頁面頻繁向后台請求數據;
2.主要用到js事件:
onmousedown() 鼠標按下時響應
onmousemove() 鼠標移動時響應
onmouseup() 鼠標彈起時響應
3.獲取頁面距離:
e.clientX
obj.offsetWidth
obj.offsetLeft
4.代碼:
html:
<div class="box"> <div class="txt">滑塊驗證</div> <div class="btn">>></div> <div class="bg"></div> </div>
css:
*{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .box{ position: relative; width:300px; height:30px; background-color: #ccc; margin:20px auto; font-size:14px; line-height:30px; box-sizing:border-box; z-index:1; } .txt{ position: absolute; left: 50%; top:0; transform: translateX(-50%); color:blue; z-index:3; } .btn{ position: absolute; top:0; left: 0; width:40px; height:30px; border:1px solid #ccc; background-color: #fff; text-align: center; line-height: 30px; cursor: move; box-sizing: border-box; z-index:4; } .bg{ position: absolute; left: 0; top:0; width:0; height:30px; background-color:green; box-sizing: border-box; z-index:2; }
js:
window.onload = function(){ var box = document.querySelector(".box"), txt = document.querySelector(".txt"), btn = document.querySelector(".btn"), bg = document.querySelector(".bg"), end = false; btn.onmousedown = function(e){ var e = e || window.event; var point = e.clientX - box.offsetLeft; btn.onmousemove = function(e){ var moveW = e.clientX - box.offsetLeft - point; btn.style.left = moveW + "px"; bg.style.width = moveW + "px"; if(btn.offsetLeft<=0){ btn.style.left = "0"; } if(btn.offsetLeft>=(box.clientWidth - btn.clientWidth)){ btn.style.left = box.clientWidth - btn.clientWidth txt.innerHTML = "驗證完成"; btn.onmousemove = null; btn.onmousedown = null; end = true; } } btn.onmouseup = function(){ btn.onmousemove = null; if(!end){ btn.style.left = "0"; bg.style.width = "0"; } } } }
5.顯示