指令禁用元素滚动行为和滚动页面

时间:2016-04-05 09:26:10

标签: javascript jquery angularjs scroll

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

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

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);
            });
        }
    }
});

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

1 个答案:

答案 0 :(得分:0)

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

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

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