gpt4 book ai didi

javascript - Knockout.JS 中的阻止滚动事件

转载 作者:行者123 更新时间:2023-11-28 11:53:03 25 4
gpt4 key购买 nike

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

为了至少做到这一点,我需要阻止浏览器的默认滚动操作。据我所知,如果您不从事件处理程序返回“true”,则 knockout 默认会执行此操作。

但是它似乎不起作用,也没有在事件上显式调用“preventDefault”。这个问题一定是滚动事件特有的。

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

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

最佳答案

向 Andrey 致敬,他指出您应该使用鼠标滚轮事件而不是滚动事件。

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

通过鼠标滚轮事件,deltaY 将为您提供滚动方向,您可以使用它来更改选择的项目:

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/

关于javascript - Knockout.JS 中的阻止滚动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31916926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com