tip:逻辑代码均有注释
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- 引入样式 -->
<link
rel="stylesheet"
href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
/>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
#app {
display: flex;
height: 100vh;
}
.content {
width: 500px;
height: 600px;
margin: auto;
background-color: green;
display: flex;
flex-direction: column;
}
.title {
flex: 1;
overflow: auto;
}
.title .fix {
position: fixed;
}
.bottom {
display: flex;
align-items: center;
justify-content: center;
background-color: pink;
height: 100px;
}
</style>
</head>
<body>
<div id="app">
<div class="content">
<div class="title" ref="box">
<div v-for="item in 100" :key="item" @click="question">{{item}}</div>
<div ref="imgRight" class="fix" v-show="showRight">苦苦</div>
</div>
<div class="bottom">no problem</div>
</div>
</div>
<script>
var vm = new Vue({
el: "#app",
data() {
return {
showRight: false,
offsetTop: null,
};
},
mounted() {
// 设置点击的dom 距离左侧的距离
// 解释: 获取大盒子距离窗口的左侧距离 -50 是我想让他距离大盒子左侧 50px
window.onload = () => {
this.$refs.imgRight.style.left =
document.querySelector(".content").offsetLeft - 50 + "px";
};
// 给大盒子添加滚动事件
this.$refs.box.addEventListener("scroll", this.handleScroll);
},
beforeDestroy() {
this.$refs.box.removeEventListener("scroll", this.handleScroll);
},
methods: {
question(e) {
this.showRight = true;
// 点击将点击的苦苦dom 保存到 offsetTop变量
this.offsetTop = e.target;
// 设置点击的苦苦dom 距离顶部窗口的高度
let rect = e.target.getBoundingClientRect();
this.$refs.imgRight.style.top = rect.y + "px";
},
handleScroll() {
if (!this.showRight) return;
// 苦苦dom 离顶部的距离 - 大盒子离顶部的距离
let difference =
this.$refs.imgRight.offsetTop - this.$refs.box.offsetTop;
// 大盒子的高度 - 苦苦dom的高度
let differenceHeight =
this.$refs.box.clientHeight - this.$refs.imgRight.clientHeight;
// 判断条件
// 1.如果 苦苦dom 距离顶部的距离小于 大盒子距离顶部的距离就消失
// 2.如果 苦苦dom 剩余距离顶部的距离 > 大盒子的高度 - 苦苦dom的高度
if (
this.$refs.imgRight.offsetTop < this.$refs.box.offsetTop ||
difference > differenceHeight
) {
this.showRight = false;
}
let rect = this.offsetTop.getBoundingClientRect().y;
this.$refs.imgRight.style.top = rect + "px";
},
},
});
</script>
</body>
</html>