class AddSlider {
constructor(elem, dir){
this.elem = elem;
this.dir = dir;
this.slider = document.getElementsByClassName(this.elem)[0];
this.sliderHandle = document.createElement('div');
}
/*Add handle to element and add styles depending on direction slider is needed to go*/
build() {
this.sliderHandle.classList.add('slider__handle');
if (this.dir === 'right') {
this.sliderHandle.style.right = 0;
this.sliderHandle.style.top = 0;
this.sliderHandle.style.width = '10px';
this.sliderHandle.style.height = '100%';
}
if (this.dir === 'bottom') {
this.sliderHandle.style.bottom = 0;
this.sliderHandle.style.width = '100%';
this.sliderHandle.style.height = '10px';
}
this.slider.appendChild(this.sliderHandle);
}
/*Add dragging class for styles when dragging, do resize sum and add it live as inline style*/
Resize(e) {
let cont = document.getElementsByClassName('slider-container')[0];
this.slider.classList.add('dragging');
this.sliderHandle.classList.add('dragging');
if(this.dir === 'right') {
this.slider.style.maxWidth = cont.offsetWidth + 'px';
this.slider.style.width = (e.clientX - this.slider.offsetLeft) + 'px';
}
if(this.dir === 'bottom') {
this.slider.style.maxHeight = '500px';
this.slider.style.height = (e.clientY - this.slider.offsetTop) + 'px';
}
}
/*Add events listeners when moving mouse and mouse up to window*/
initResize() {
window.addEventListener('mousemove', this.Resize.bind(this));
window.addEventListener('mouseup', this.stopResize.bind(this));
}
/*Remove event listeners and classes*/
stopResize() {
console.log('STOPPED!!!');
this.slider.classList.remove('dragging');
this.sliderHandle.classList.remove('dragging');
window.removeEventListener('mousemove', this.Resize);
window.removeEventListener('mouseup', this.stopResize);
}
/*init*/
init() {
this.build();
this.sliderHandle.addEventListener('mousedown', this.initResize.bind(this));
}
}
let componentSlider = new AddSlider('slider', 'bottom');
componentSlider.init();
有人知道为什么resize函数一直在运行,而stopResize函数不会永久删除类和窗口监听器吗? stopResize函数控制器记录文本并删除类,但类会立即添加回来,滑块不会停止移动。