简体   繁体   English

如何在使用eventListener的“滚动”后修复滚动头

[英]how to fix header on scroll after using eventListener' scroll'

In my Html code, I want to make a header to be fixed-top when scrolled. 在我的HTML代码中,我想使标题在滚动时固定在顶部。 It is working fine when I write javascript code within body tag.but when I'm creating a new .js file & writing .js file path in script tag then the page doesn't scroll down 当我在body标签中编写javascript代码时效果很好,但是当我创建新的.js文件并在script标签中编写.js文件路径时,页面不会向下滚动

enter code here
const nav = document.getElementById("main")
        let topOfNav = nav.offsetTop;
            function fixNav() {
                if (window.pageYOffset >= topOfNav) {

                   nav.classList.add('fixed-nav')
                } else {
                    nav.classList.remove('fixed-nav')

                }
            }
            window.addEventListener('scroll', fixNav)
     .fixed-nav {
      position: fixed;
    top: 0;
    left: 0;
    width: 100%; 
            }
 <nav class="navbar  navbar-expand-lg navbar-light" id="main">
                        <a class="navbar-brand" href="index.html">
                            <img class="top_logo" src="logo.jpg"                    
                             alt="">TestMyCode
                        </a>
 </nav>
 <script src="theme.js"></script>

I have written this after jQuery,popper.js and bootstrap.min.js. 我是在jQuery,popper.js和bootstrap.min.js之后编写的。 Initially in header I have added 最初我在标题中添加了

enter code here

But page stops scrolling.It stucks at top position.how to make it scroll when js added through script tag? 但是页面停止滚动。它卡在顶部位置。当通过脚本标签添加js时如何使其滚动?

Based on your html you wrote this: 根据您的html,您编写了以下代码:

<script src="theme.js"></script>

Try doing it like this... 尝试这样做...

   <html>
        <head>
           <script type = "text/javascript" src = "filename.js" ></script>
   </head>

        <body>
      .......
        </body>
   </html>

It is also important to note that if you have the file inside a folder you need to account for that in the src If it is not the file directories you will need to provide the absolute file path 同样重要的是要注意,如果文件位于文件夹中,则需要在src中说明该文件。如果不是文件目录,则需要提供绝对文件路径

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

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