简体   繁体   English

将 jQuery 转换为 Vanilla javaScript 时出现滚动问题

[英]Having scrolling issue when converting jQuery to Vanilla javaScript

I'm converting this simple scrolling code from jQuery to vanilla Javascript but having small issues when selecting the elements.我正在将这个简单的滚动代码从 jQuery 转换为 vanilla Javascript,但在选择元素时有一些小问题。 Can anyone point me in the right direction?谁能指出我正确的方向? Thanks a lot in advance!提前非常感谢!

Here's working jQuery code:这是工作 jQuery 代码:

jQuery LIVE DEMO jQuery 现场演示

Now here's my vanilla Javascript code:现在这是我的香草 Javascript 代码:

window.addEventListener('scroll', function() {
  document.querySelectorAll('.target').forEach(function(item, index){
      if($(window).scrollTop() >= $(this).offset().top) {
         var id = $(this).attr('id');
         document.querySelector('#nav nav a').classList.remove('active');
         document.querySelector('#nav nav a[href=#'+ id +']').classList.add('active');
     }
 });
});

Vanilla JavaScript Demo:香草 JavaScript 演示:

JavaScript DEMO JavaScript 演示

I removed the binding by attribute id by making the binding by index (At my discretion):我通过按索引进行绑定(由我自行决定)删除了按属性id的绑定:

document.querySelectorAll("#nav nav a")[index].classList.add("active");

Also, I inserted an internal forEach() to remove the active class everywhere, with the subsequent receipt of the active class for the current one.此外,我插入了一个内部forEach()以删除所有的活动class,随后收到当前活动class。

$(window).scrollTop() replaced by window.pageYOffset ; $(window).scrollTop()替换为window.pageYOffset

$(this).offset().top replaced by item.offsetTop . $(this).offset().top替换为item.offsetTop

window.addEventListener("scroll", function () {
    document.querySelectorAll(".target").forEach(function (item, index) {
        if (window.pageYOffset >= item.offsetTop) {
            document.querySelectorAll("#nav nav a").forEach(function (a_del) {
                a_del.classList.remove("active");
            });
            document.querySelectorAll("#nav nav a")[index].classList.add("active");
        }
    });
});

Also, in your html, some covering <div> do not contain / , like a closed </div> .此外,在您的 html 中,一些覆盖<div>不包含/ ,例如封闭的</div> Like that:像那样:

<section id="main">
    <div class="target" id="1">TARGET 1</div>
    <div>item 1</div>
    <div>item 1<div>   <===
    <div>item 1<div>   <===
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM