放置位置:固定的行为,例如粘性(对于Vue2) [英] Make position: fixed behavior like sticky (for Vue2)

查看:76
本文介绍了放置位置:固定的行为,例如粘性(对于Vue2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

位置:粘性大多数移动浏览器都不支持。但是 position:fixed 并不是我所需要的(因为固定块与文档底部的内容重叠)。

Position: sticky doesn't support by the most mobile browsers. But position: fixed is not that thing I need (because of fixed block overlaps content in the bottom of document).

我猜对于jquery,如果我们将文档滚动到底部,将很容易为固定块设置静态位置。

I guess for jquery it will be easy to set static position for fixed block if we get bottom of document onscroll.

但是对于Vue2,我不知道如何做同样的事情。请给一些建议。也许存在更好的解决方案。

But for Vue2 I haven't any idea how to do the same. Give some advice please. Or maybe better solution exists.

推荐答案

正如我在评论中提到的,我建议尽可能使用polyfill。他们将付出很多努力来确保正确。但是,这里简单介绍一下如何在Vue中进行操作。

As I mentioned in the comments, I'd recommend using a polyfill if at all possible. They will have put a lot of effort into getting it right. However, here is a simple take on how you might do it in Vue.

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

I have the application handle scroll events by putting the scrollY value into a data item. My sticky-top component calculates what its fixed top position would be, and if it's > 0, it uses it. The widget is 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>

这篇关于放置位置:固定的行为,例如粘性(对于Vue2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆