指示禁用元素滚动行为并改为滚动页面

Directive to disable element scrolling behavior and scroll page instead

本文关键字:滚动 元素 指示      更新时间:2024-01-09

我要做的是创建一个指令,当放置在元素上(例如选择下拉列表)时,该指令将禁用该元素的鼠标滚轮滚动,而是滚动页面。我设法找到了两种方法,但都不完整。

当焦点在元素上时,这不允许滚动页面(它禁用所有滚动)

over.directive('disableSelectScroll', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attributes) {
            element.on('mousewheel', function (e) {
                return false;
            })
        }
    }
});

这对firefox和chrome有效,但对IE(11)无效

over.directive('disableSelectScroll', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attributes) {
            ['touchstart', 'touchmove', 'touchend', 'keydown', 'wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) {
                element.unbind(eventName);
            });
        }
    }
});

当元素接收到鼠标滚轮事件或以某种方式链接到页面滚动行为时,我是否必须重新定义滚动行为?

我已经找到了解决这个问题的部分方法。在我的用例中,只有当某个元素被聚焦时,才会在该元素内滚动。从元素中移除焦点,鼠标滚轮事件应该向上传播。以下代码提供了令人满意的结果:

over.directive('disableSelectScroll', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attributes) {
            element.on('mousewheel', function () {
                element.blur();
            });
        }
    }
});

此解决方案的缺点是滚动时下拉列表会关闭。