在knockout.JS 中阻止滚动事件 [英] Block scroll event in knockout.JS

查看:14
本文介绍了在knockout.JS 中阻止滚动事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在溢出区域重新实现滚动功能,以便鼠标滚轮更改当前选择而不是滚动位置.

I need to reimplement the scroll functionality over an overflow area, so that the mousewheel changes the current selection rather than the scroll position.

至少要做到这一点,我需要阻止浏览器的默认滚动操作.据我所知,如果您不从事件处理程序返回true",则默认情况下淘汰赛会执行此操作.

To do this at the very least, I need to block the default scroll action of the browser. From what I can tell knockout does this by default, provided that you don't return 'true' from the event handler.

但是它似乎不起作用,也没有显式调用事件的preventDefault".此问题必须特定于滚动事件.

However it doesn't seem to work, nor does calling 'preventDefault' on the event explicitly. This problem must be specific to the scroll event.

scrolled: function (vm, event) {
    event.preventDefault();
    return false;
}

示例:http://jsfiddle.net/vjLqauq5/2/

推荐答案

感谢 Andrey 指出您应该使用鼠标滚轮事件而不是滚动事件.

Hat tip to Andrey for pointing out that you should use the mousewheel event rather than the scroll event.

<div class="container" data-bind="foreach: items, event: { mousewheel: scrolled }">

从鼠标滚轮事件中,deltaY 会给你滚动方向,你可以用它来改变被选中的项目:

From the mousewheel event, deltaY will give you the scroll direction, which you can use to change which item is selected:

scrolled: function (vm, event) {
    var direction = Math.sign(event.deltaY), // 1 is down, -1 is up
        maxIdx = vm.items().length - 1,
        selectedIdx = vm.items.indexOf(vm.selected()) + direction;
    if (selectedIdx >= 0 && selectedIdx <= maxIdx) {
        vm.selected(vm.items()[selectedIdx]);
    }
    // return false; // implied as long as you don't return true
}

http://jsfiddle.net/vjLqauq5/8/

这篇关于在knockout.JS 中阻止滚动事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆