当前位置 : 主页 > 网络编程 > JavaScript >

纯js实现兼容所有浏览器的滚轮事件

来源:互联网 收集:自由互联 发布时间:2021-06-30
addWheelListener.js /** * usage: * addWheelListener(elem, function(e) { * console.log(e.deltaY); * e.preventDefault(); * }); */(function (window, document) { let prefix = '', _addEventListener, onwheel, support; // 检测事件模型 if (wi
addWheelListener.js
/**
 * usage: 
 * addWheelListener(elem, function(e) {
 *     console.log(e.deltaY);
 *     e.preventDefault(); 
 * });
 */
(function (window, document) {

    let prefix = '', _addEventListener, onwheel, support;

    // 检测事件模型
    if (window.addEventListener) {
        _addEventListener = 'addEventListener';
    } else {
        _addEventListener = 'attachEvent';
        prefix = 'on';
    }

    // 检测wheel事件能否被支持
    support = 'onwheel' in document.createElement('div') ? 'wheel' : // 各个厂商的高版本浏览器都支持"wheel"
        document.onmousewheel !== undefined ? 'mousewheel' : // Webkit 和 IE一定支持"mousewheel"
            'DOMMouseScroll'; // 低版本firefox

    const addWheelListener = function (ele, callback, useCapture) {
        _addWheelListener(ele, support, callback, useCapture);

        // 旧版本Firefox使用MozMousePixelScroll
        if (support === 'DOMMouseScroll') {
            _addWheelListener(ele, 'MozMousePixelScroll', callback, useCapture);
        }
    };

    function _addWheelListener (elem, eventName, callback, useCapture) {
        elem[_addEventListener](prefix + eventName, support === 'wheel' ? callback : function (originalEvent) {
            !originalEvent && ( originalEvent = window.event );

            // 创建统一的事件对象
            let event = {
                originalEvent: originalEvent,  // 保留对原事件对象的引用
                target: originalEvent.target || originalEvent.srcElement,
                type: 'wheel',
                deltaMode: originalEvent.type === 'MozMousePixelScroll' ? 0 : 1,
                deltaX: 0,
                deltaZ: 0,
                preventDefault: function () {
                    originalEvent.preventDefault ? originalEvent.preventDefault() : originalEvent.returnValue = false;
                }
            };

            // calculate deltaY (and deltaX) according to the event
            if (support === 'mousewheel') {
                event.deltaY = -1 / 40 * originalEvent.wheelDelta;
                // Webkit also support wheelDeltaX
                originalEvent.wheelDeltaX && ( event.deltaX = -1 / 40 * originalEvent.wheelDeltaX );
            } else {
                event.deltaY = originalEvent.detail;
            }

            // 将重写后的事件对象作为参数传递给回调函数并返回
            return callback(event);

        }, useCapture || false);
    }

    module.exports = {
        addWheelListener: addWheelListener
    };

})(window, document);
网友评论