简体   繁体   English

如何动画导航栏返回网站顶部?

[英]How can I animate a navbar going back to the top of the website?

Right now, I have successfully animated the navbar when scrolling down on the page.现在,我已经成功地在页面上向下滚动时为导航栏设置了动画。 However, when I go back to the top, it resets immediately, so it's not as smooth of a website as I'd like.但是,当我 go 回到顶部时,它会立即重置,所以它不像我想要的那样流畅。 Can anybody help me with this using Javascript?任何人都可以使用 Javascript 帮助我吗? Here's what I have so far:这是我到目前为止所拥有的:

JavaScript JavaScript

$(function () {
  $(document).scroll(function () {
      var $nav = $(".topnav");
      $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
    });
  $(document).scroll(function () {
      var $nav = $(".topnav");
      $nav.toggleClass('unscrolled', $(this).scrollTop() == $nav.height());
    });
});

CSS CSS

    .topnav.scrolled {
        background-color: #000000;
        transition: background-color 200ms linear;
    }
    .topnav.unscrolled {
        background-color: transparent;
        transition: background-color 200ms linear;
    }

The "unscrolled" section doesn't work, so you can ignore it. “未滚动”部分不起作用,因此您可以忽略它。

Without seeing the definition of your CSS classes, I wonder if the 'unscrolled' is added along with the 'scrolled' causing a conflict.在没有看到 CSS 类的定义的情况下,我想知道是否添加了“未滚动”以及“滚动”导致冲突。

Can we see where you declare both .scrolled and .unscrolled ?我们能看到你在哪里声明.scrolled.unscrolled吗?

In the meantime, not knowing anything else, I would try like so:与此同时,我什么都不知道,我会这样尝试:

$(function () {
  $(document).scroll(function () {
      var $nav = $(".topnav");
      $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height()); // add class 'scrolled' when doc.scrollTop > nav.height, remove when not
      $nav.toggleClass('unscrolled', $(this).scrollTop() <= $nav.height()); // add scroll 'unscrolled' when doc.scrollTop <= nav.height, remove when hot
    });
});

I usually use jQuery and have the header as fixed in the css and then this adds a class on scroll when the user has scrolled half way down the page so it is not instantly changing on scroll. I usually use jQuery and have the header as fixed in the css and then this adds a class on scroll when the user has scrolled half way down the page so it is not instantly changing on scroll.

 $(window).scroll(function() {

    var $topNav = $(".topnav"),
        $scroll = $(window).scrollTop(),
        $wh = window.innerHeight / 2;

    if ($scroll > $wh) {
        $topNav.addClass("scrolled");
    } else {
        $topNav.removeClass("scrolled");
    }

});

You can change $wh to whatever you want, number or pixels from top etc...您可以将 $wh 更改为您想要的任何内容,顶部的数字或像素等...

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

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