首页 > 解决方案 > 鼠标滚轮上的 JS scrollIntoView 功能不起作用

问题描述

我有上面的脚本,它在浏览器控制台上输出正确的 id,但不滚动:

var divID = null;
var up = null;
var down = null;

function div(x) {
    switch(x.id) {
        case 's1':
            up = null;
            down = 's2';
            break;
        case 's2':
            up = 's1';
            down = 's3'
            break;
        case 's3':
            up = 's2';
            down ='s4';
            break;
        case 's4':
            up = 's3';
            down = null;
            break;
        default:
            up = null;
            down = null;
            break;
    }
}

window.addEventListener('wheel', function(e) {          
    if (e.deltaY < 0 && up) {
        console.log(up);
        document.getElementById(up).scrollIntoView();
    }
    if (e.deltaY > 0 && down) {
        console.log(down);
        document.getElementById(down).scrollIntoView();
    }
});

我正在使用这种结构:

<div id='s1' onmouseover="div(this)">
    <!--content-->
</div>
<div id='s2' onmouseover="div(this)">
    <!--content-->
</div>
<div id='s3' onmouseover="div(this)">
    <!--content-->
</div>
<div id='s4' onmouseover="div(this)">
    <!--content-->
</div>

正如我所说,console.log 打印它应该打印的内容,但滚动什么也不做,只是常规滚动。如果重要,我正在使用 wordpress。

标签: javascripthtml

解决方案


这里的问题是,在某些浏览器和操作系统中,滚动到一个元素不会激活该元素的悬停状态。此外,如果有人拖动滚动条,它永远不会激活您的悬停。

这里的悬停告诉你的滚动事件去哪里,但它们需要悬停动作才能生效。您最好使用它们的 offsetTop 值找到正确的元素,而不是在滚动期间需要第二个事件。

[编辑] 或者滚动事件的滚动覆盖了 scrollIntoView 方法的潜力。因为,您似乎只想进行滚动劫持运动,请尝试e.preventDefault()在滚动事件中添加一个。


推荐阅读