【问题标题】:Make position: fixed behavior like sticky (for Vue2)制作位置:固定行为,如粘性(适用于 Vue2)
【发布时间】:2018-02-20 11:27:05
【问题描述】:

Position: sticky 不被大多数移动浏览器支持。但是position: fixed 不是我需要的东西(因为固定块与文档底部的内容重叠)。

我猜对于 jquery 来说,如果我们得到文档滚动条的底部,那么为固定块设置静态位置会很容易。

但是对于 Vue2,我不知道该怎么做。请给一些建议。或者也许存在更好的解决方案。

【问题讨论】:

标签: css vue.js vuejs2 css-position sticky


【解决方案1】:

正如我在 cmets 中提到的,我建议尽可能使用 polyfill。他们会付出很多努力来让它正确。不过,这里有一个关于如何在 Vue 中执行此操作的简单介绍。

我让应用程序通过将 scrollY 值放入数据项来处理滚动事件。我的sticky-top 组件计算它的固定顶部位置,如果它 > 0,它会使用它。小部件是position: relative

new Vue({
  el: '#app',
  data: {
    scrollY: null
  },
  mounted() {
    window.addEventListener('scroll', (event) => {
      this.scrollY = Math.round(window.scrollY);
    });
  },
  components: {
    stickyTop: {
      template: '<div class="a-box" :style="myStyle"></div>',
      props: ['top', 'scrollY'],
      data() {
        return {
          myStyle: {},
          originalTop: 0
        }
      },
      mounted() {
        this.originalTop = this.$el.getBoundingClientRect().top;
      },
      watch: {
        scrollY(newValue) {
          const rect = this.$el.getBoundingClientRect();
          const newTop = this.scrollY + +this.top - this.originalTop;

          if (newTop > 0) {
            this.$set(this.myStyle, 'top', `${newTop}px`);
          } else {
            this.$delete(this.myStyle, 'top');
          }
        }
      }
    }
  }
});
#app {
  height: 1200px;
}

.spacer {
  height: 80px;
}

.a-box {
  display: inline-block;
  height: 5rem;
  width: 5rem;
  border: 2px solid blue;
  position: relative;
}
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <div class="spacer"></div>
  <div class="a-box"></div>
  <sticky-top top="20" :scroll-y="scrollY"></sticky-top>
  <div class="a-box"></div>
</div>

【讨论】:

  • @Boern 为什么你将答案还原为包含未使用的变量?
  • haha :) 因为还有更多,我既不想发布不完整的修订版,也没有信心在未经您同意的情况下修改您的大部分代码(此处为 JS noob)。另外,我不想提交自己的解决方案并窃取您的代表。
【解决方案2】:

这似乎对我有用

...

  <header
    ref="header"
    class="header-container"
    :class="{ 'header-container--sticky': isHeaderSticky }"
  >

...

...

data() {
    return{
      scrollY: null,
      headerTop: 0,
      isHeaderSticky: false,
    }
  },
  mounted() {
    window.addEventListener('load', () => {
      window.addEventListener('scroll', () => {
        this.scrollY = Math.round(window.scrollY);
      });
      this.headerTop = this.$refs.header.getBoundingClientRect().top;
    });
  },
  watch: {
    scrollY(newValue) {
      if (newValue > this.headerTop) {
        this.isHeaderSticky = true;
      } else {
        this.isHeaderSticky = false;
      }
    }
  }

...

...

.header-container {
      &--sticky {
        position: sticky;
        top: 0;
        z-index: 9999;
      }
    }

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 2021-09-03
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    相关资源
    最近更新 更多