Block scroll event in knockout.JS

2020-05-01 08:11发布

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

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.

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

Example: http://jsfiddle.net/vjLqauq5/2/

1条回答
放我归山
2楼-- · 2020-05-01 08:49

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 }">

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/

查看更多
登录 后发表回答