作者:蟹子的宿命 | 来源:互联网 | 2023-10-11 14:20
各位,我想做一个滑块验证插件,但是当鼠标弹起_mouseUp的时候,无法移除_mouseMove和_mouseUp事件,难道绑定时候的函数和解除时候的函数不是同一个么?
各位,我想做一个滑块验证插件,但是当鼠标弹起_mouseUp的时候,无法移除_mouseMove和_mouseUp事件,难道绑定时候的函数和解除时候的函数不是同一个么?
1 2 3 4
| var verify = new SlideVerify({
el: '.drag-wrapper',
slider: '.drag-block'
}) |
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
| function SlideVerify (obj) {
this.wrapper = document.querySelector(obj.el)
this.wrapperWidth = this.wrapper.clientWidth
this.slider = document.querySelector(obj.slider)
this.sliderWidth = this.slider.clientWidth
this.isPass = false; // 是否通过验证
this.left = 0;
this.x = 0;
this._init();
}
SlideVerify.prototype = {
constructor: SlideVerify,
_init: function(){
this.slider.addEventListener('mousedown', this._mouseDown.bind(this))
},
_mouseDown: function(e){
if (e.which === 1) { // 鼠标左键
this.x = e.pageX;
document.addEventListener('mousemove', this._mouseMove.bind(this))
document.addEventListener('mouseup', this._mouseUp.bind(this))
}
},
_mouseMove: function(e){
this.left = (e.pageX - this.x);
if ( this.left >= 0 && this.left <= (this.wrapperWidth - this.sliderWidth)) {
this.slider.style.left = this.left + 'px';
} else if (this.left <0) {
this.slider.style.left = '0px'
} else if (this.left > (this.wrapperWidth - this.sliderWidth)) {
this.slider.style.left = (this.wrapperWidth - this.sliderWidth) + 'px'
}
},
_mouseUp: function(){
console.log(document)
document.removeEventListener('mousemove', this._mouseMove)
document.removeEventListener('mouseup', this._mouseUp)
let isPass = this.left <(this.wrapperWidth - this.sliderWidth)
if (isPass) { // 没有通过
console.log('不通过')
this.slider.style.left = '0px'
this.left = 0;
} else { // 验证通过
console.log('通过')
this.slider.style.left = (this.wrapperWidth - this.sliderWidth) + 'px'
this.isPass = true
this.slider.removeEventListener('mousedown', this._mouseDown)
}
return this;
}
} |