html代码部分:
<div id="wrapper"><div id="drop_box"><span class="iconfont icon-jiantouyou" id="spanBox"></span></div><p id="text">拖动滑块验证</p><div id="bg"></div></div>
CSS部分:
*{margin: 0;padding: 0;}#wrapper{width: 300px;height: 30px;background: #9F9F9F;text-align: center;line-height: 30px;margin: 20px auto;position: relative;}#drop_box{width: 40px;height: 30px;background-color: #ddd;position: absolute;z-index:1000}#bg{height: 30px;background: #0BB20C;position: absolute;left: 0px;top: 0px;}#text{position: relative;z-index: 999;}
JS部分:
window.onload = function(){var dropBox = document.querySelector('#drop_box');var wrapper = document.querySelector('#wrapper');var text = document.querySelector('#text');var bg = document.querySelector('#bg');var spanBox = document.querySelector('#spanBox');var classVal = document.getElementById("spanBox").getAttribute("class");classVal = classVal.replace("icon-jiantouyou","icon-zhengque");var flag = false;//验证是否正确dropBox.onmousedown = function(event){var downX = event.clientX;//鼠标按下去的clientXdropBox.onmousemove = function(event){var moveX = event.clientX - downX;//鼠标移动的clientXif(moveX > 0){this.style.left = moveX + 'px';bg.style.width = moveX + 'px';if(moveX >= wrapper.offsetWidth - this.offsetWidth ){flag = true;text.innerText = '通过验证';text.style.color = '#fff';spanBox.setAttribute("class",classVal );//添加正确通过的icon类this.onmousemove = null;//移除移动事件this.onmousedown = null;//移除鼠标按下事件}}}};//松开dropBox.onmouseup = function(event){this.onmousemove = null;if(flag) return;this.style.left = 0;bg.style.width = 0;}}