非重点的代码, 比如样式啥的, 我就不放上来了, 一笔带过
简略的写一下 HTML 代码, 可以对照文章最后的效果图看, 应该不难理解
- <div :style="{ paddingBottom: paddingBottom}">
- <header > 资源信息 </header>
- <div>
- <!-- 公司信息 浏览量 -->
- </div>
- <div id="fixedBar" :class="{ fixedBar: isFixed }">
- <!-- 品名 -->
- <!-- 规格 -->
- <!-- 产地 -->
- <!-- 单价 -->
- </div>
- <div :style="{ marginTop: marginTop }">
- <!-- 数据列表 -->
- </div>
- <footer class="footer">
- <button > 订阅 </button>
- <button > 关闭 </button>
- <div v-show="advertShow">
- <a @click="del">*</a>
- <img src="./ 广告. jpg" />
- </div>
- </footer>
- </div>
- <style>
- .fixedBar {
- position: fixed;
- top: 0;
- z-index: 999;
- width: 100%;
- }
- </style>
- vue
- data ()
- data () {
- paddingBottom: '1.5rem', // 给最外层 div 一个 padding-bottom
- // 因为 footer 是 fixed 定位 如果 padding-bottom 为 0 数据列表拉到最下面的时候 会有部分数据被 footer 挡住
- isFixed: false, // bar 浮动
- offsetTop: 0, // 触发 bar 浮动的阈值
- marginTop: 0, // 触发 bar 浮动的同时 给数据列表一个 margin-top 防止列表突然上移 会很突兀
- advertShow: true, // 广告显示
- }
- mounted ()
- mounted () {
- // 设置初始的 padding-bottom 值为 footer 的高度 +20 防止数据列表拉到最下面被 footer 挡住 + 多少自定
- this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
- // 设置 bar 浮动阈值为 #fixedBar 至页面顶部的距离
- this.offsetTop = document.querySelector('#fixedBar').offsetTop;
- // 开启滚动监听
- Windows.addEventListener('scroll', this.handleScroll);
- }
- methods
- methods: {
- // 关闭广告
- del () {
- this.advertShow = true;
- this.$nextTick(() => {
- this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
- });
- },
- // 滚动监听 滚动触发的效果写在这里
- handleScroll () {
- var scrollTop = Windows.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
- if (scrollTop>= this.offsetTop) {
- this.isFixed = true;
- this.marginTop = document.querySelector('#fixedBar').offsetHeight + 'px';
- } else {
- this.isFixed = false;
- this.marginTop = 0;
- }
- }
- 4. destroyed ()
- destroyed () {
- Windows.removeEventListener('scroll', this.handleScroll); // 离开页面 关闭监听 不然会报错
- }
效果图
最后
为了帮助大家让学习变得轻松, 高效, 给大家免费分享一大批资料, 帮助大家在成为全栈工程师, 乃至架构师的路上披荆斩棘. 在这里给大家推荐一个前端全栈学习交流圈: 866109386. 欢迎大家进群交流讨论, 学习交流, 共同进步.
当真正开始学习的时候难免不知道从哪入手, 导致效率低下影响继续学习的信心.
但最重要的是不知道哪些技术需要重点掌握, 学习时频繁踩坑, 最终浪费大量时间, 所以有有效资源还是很有必要的.
来源: http://www.qdfuns.com/article/51070/7fb1f1fb9c32749d571a36ad4b8b7251.html