vue模仿twitter写一个自己的博客——中部导航栏布局

接下来是中部导航栏。我们看到这里的头像动画,和中部导航栏定位都是跟鼠标滚动有关的。我们先将布局实现一下。这里是要求在页面上部分滚动范围内,导航栏一直在div的上部,随着鼠标的滚动而改变位置。到下部分滚动范围,导航栏就一直固定到页面的上部分。
这里需要注意两个地方

  1. 这里需要一个覆盖不了的区域,可以给人一种更好开关屏的感觉。而且中部导航栏下方区域的内容,在下滑的时候不能出现在这个区域。
    在这里插入图片描述
  2. 一定要注意尽可能的少进行DOM操作,这样是非常影响性能的

监听鼠标滚动事件

  private fixedFlag: boolean = false;
  private unFixedFlag: boolean = true;
  private mounted() {
    window.addEventListener("scroll", this.handleScroll);
  }
  private handleScroll() {
    const scrollTop =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop;
    if (scrollTop > 300) {
      if (!this.fixedFlag) {
        const obj = document!.getElementById("index-menu");
        const obj2 = document!.getElementById("fake-area");
        obj!.style.position = "fixed";
        obj!.style.top = "77px";
        obj2!.style.position = "fixed";
        obj2!.style.top = "47px";
        this.fixedFlag = true;
        this.unFixedFlag = false;
      }
    } else {
      if (!this.unFixedFlag) {
        const obj = document!.getElementById("index-menu");
        const obj2 = document!.getElementById("fake-area");
        obj!.style.position = "";
        obj!.style.top = "";
        obj2!.style.position = "";
        obj2!.style.top = "";
        this.unFixedFlag = true;
        this.fixedFlag = false;
      }
    }
  }

效果展示

在这里插入图片描述

项目地址

https://github.com/pppercyWang/twitter-blog-vue

发布了51 篇原创文章 · 获赞 18 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42565137/article/details/97621172
今日推荐