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

查看:119
本文介绍了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 }">

在mousewheel事件中,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天全站免登陆