我们实现的就是这种效果(请忽视博主的水印,充不起vip啊),下面放代码:
<template> <div class="hello"> <div class="myTop"> <ul> <li>hello</li> <li>marry</li> <li>abc</li> <li>cat</li> </ul> </div> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>手机号</th> <th>状态</th> </tr> </thead> <tbody> <tr v-for="(item,index) in tableData" :key="index"> <td>{{item.name}}</td> <td>{{item.age}}</td> <td>{{item.sex}}</td> <td>{{item.phone}}</td> <td>{{item.state}}</td> </tr> </tbody> </table> </div> </template> <script> export default { name: "HelloWorld", data() { return { tableData: [ { name: "lisa", age: 17, sex: "women", phone: 1387079272, state: "有效" }, { name: "maria", age: 15, sex: "women", phone: 1677119131, state: "有效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sunny", age: 19, sex: "men", phone: 1380012312, state: "有效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" }, { name: "sam", age: 21, sex: "man", phone: 1389643753, state: "无效" } ], offsetTop:0, offsetHeight:0 }; }, mounted() { window.addEventListener("scroll", this.handleScroll); this.$nextTick(function(){ var body = document.getElementsByClassName('hello')[0]; var div = document.getElementsByClassName("myTop")[0]; // console.log(body.scrollTop,div.scrollHeight) this.offsetTop = div.offsetTop; this.offsetHeight = div.offsetHeight; console.log("offsetTop:" + this.offsetTop + "," + this.offsetHeight); }); }, destroyed() { window.removeEventListener("scroll", this.handleScroll); }, methods: { handleScroll() { let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; var div = document.getElementsByClassName("myTop")[0]; // console.log(scrollTop) if(scrollTop>(this.offsetHeight - this.offsetTop)){ div.classList.add('getTop'); div.classList.remove('noTop'); } else{ div.classList.remove('getTop'); div.classList.add('noTop') } } } }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped lang='less'> @import "./hello.less"; </style>这个方法其实和网上的大部分是相同的就是监听scroll然后根据界限进行变化,但是按照网上的一些方法,position:fixed即使监听回去了他这个也是无法消除的,于是我添加了一个新css(我使用的是less):
.noTop{ position: relative; top:0; left: 0; }如果回到上面他的position变成relative就解决了这个问题,同时我给他吸顶的同时添加了动画:
// 吸顶样式 .getTop{ top:-52px; animation-name: myAnimate; animation-duration: 0.3S; animation-timing-function:linear; animation-iteration-count:1; position: fixed; animation-fill-mode: forwards; } @keyframes myAnimate{ 0%{ } 100%{ top: 0px; } }模仿的是网易严选的吸顶,如果有疑问或者不懂得随时dd~~