scrollIntoView在Chrome上无法正常运行,但在Firefox中可以正常运行

时间:2019-03-21 08:41:32

标签: javascript js-scrollintoview

我已经解决了有关scrollIntoView的问题。我编写的代码适用于Firefox,但不适用于Chrome。我没有从控制台收到任何错误或任何内容,因此我不知道这是什么问题。如何在Chrome上正确运行?我想在Vanilla JS中解决它

这是我的代码-> https://codepen.io/Rafi-R/pen/PLdvjO

const body = document.querySelector('body');
const links = document.querySelectorAll(".link");
let section = 0;

const scrollDirection = e => e.wheelDelta ? e.wheelDelta : -1 * e.deltaY;

const scrollToSection = e => {
    e.preventDefault();
    section = 
        scrollDirection(e) < 0 
        ? (section + 1 >= links.length - 1 ? section = links.length - 1 : section + 1) 
        : (section - 1 <= 0 ? section = 0 : section - 1);   

    let element = document.querySelector(links[section].getAttribute("href"));
    scrollToTheView(element);
}

const scrollToTheView = el => {
    el.scrollIntoView({ behavior: 'smooth' });
    console.log(el, links[section].getAttribute("href"), section)
}

body.addEventListener('wheel', scrollToSection, { passive: false });

打开Codepen的控制台时,console.log()崩溃scrollIntoView({behavior: 'smooth'}),因此滚动无法正常工作。

2 个答案:

答案 0 :(得分:0)

您没有说您期望发生什么,但是您的Codepen对我来说似乎很好。每次向下滚动鼠标滚轮时,下一部分就会滑入视图。

这是Ubuntu上的Chrome 73.0.3683.86。

答案 1 :(得分:0)

Chrome浏览器不接受scrollIntoView方法中的所有选项。我遇到了类似的问题,发现如果您更改这些选项的值似乎还可以。

element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });

上面的代码段对我来说可以水平滚动元素

Refer the browser compatibility section in the MDN for scrollIntoView

相关问题