1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| function Drag(conf){
this.btn = this.getDom(conf.btn);
this.bg = this.getDom(conf.bg);
this.text = this.getDom(conf.text);
this.box = this.getDom(conf.box );
this.width = this.box.offsetWidth;
this.maxLeft = this.getDom(conf.box).offsetWidth - this.btn.offsetWidth;
this.startX = 0;
this.isDown = false;
this.success = typeof conf.success == 'function' ? conf.success : null;
this.mousedown = this.mousedown.bind(this);
this.mousemove = this.mousemove.bind(this);
this.mouseup = this.mouseup.bind(this);
this.remove = this.remove.bind(this);
this.btn.addEventListener('mousedown',this.mousedown,null);
document.addEventListener('mousemove',this.mousemove,null);
document.addEventListener('mouseup',this.mouseup,null)
}
Drag.prototype = {
getDom:document.querySelector.bind(document),
getDomAll:document.querySelectorAll.bind(document),
mousedown:function (e){
this.startX = e.clientX;
this.isDown = true;
},
mousemove:function (e){
if(!this.isDown) return false;
var left = e.clientX - this.startX;
if(left > 0){
this.btn.style.left = left + 'px';
this.bg.style.width = left + 'px';
if(left >= this.maxLeft){
this.text.innerText = '验证通过';
this.text.style.color = '#fff';
this.remove();
}
}
},
remove:function (){
this.isDown = false;
this.btn.removeEventListener('mousedown',this.mousedown,null);
document.removeEventListener('mousemove',this.mousemove,null);
document.removeEventListener('mouseup',this.mouseup,null);
if(this.success != null){
this.success();
}
},
mouseup:function (e){
var clientX = e.clientX - this.startX;
if(clientX < this.maxLeft){
this.isDown = false;
this.btn.style.left = 0 + 'px';
this.bg.style.width = 0 + 'px';
}else{
//this.remove.call(this);
}
}
}
function init(){
var drag = new Drag({
box:'#box',
btn:'.btn',
bg:'.bg',
text:'.text',
success:function(){
console.log('验证成功')
}
});
}
document.addEventListener('readystatechange',init,null)
! |
共 0 条评论关于"原生js实现拖动滑块验证_封装版"
最新评论