应业务需求,顺手写了个轮子
兼容性应该不差
这个是
TS
版的,要用到JS
里面的话要稍做调整
export class WheelDirective {
private el: HTMLElement;
constructor(nativeElement : HTMLElement) {
this.el = nativeElement;
this.handleWheelEvent();
}
handleWheelEvent () {
const event = window.addEventListener ? 'addEventListener' : 'attachEvent';
let wheel = '';
if ('onmousewheel' in this.el) {
wheel = 'mousewheel';
} else if ('onwheel' in this.el) {
wheel = 'wheel';
} else if ('attachEvent' in window) {
wheel = 'onmousewheel';
} else {
wheel = 'DOMMouseScroll';
}
this.el[event](wheel, this.scroll);
}
scroll = (event) => {
if (this.el.clientWidth >= this.el.scrollWidth) { return; }
event.preventDefault();
this.el.scrollLeft += event.deltaY
? event.deltaY
: (event.detail && event.detail !== 0)
? event.detail
: -event.wheelDelta;
}
}
API
const Ele = document.getElementById('ID');
new WheelDirective(Ele);