<div class="demo">
<div class="handr"></div>
<div class="banner"></div>
<div class="bodyr"></div>
<div class="loos">
<span>返回顶部</span>
</div>
</div>
* {
padding: 0px;
margin: 0px;
}
.demo {
/* position: relative; */
margin: 5px auto;
width: 600px;
}
.handr {
width: 100%;
height: 100px;
background-color: aquamarine;
}
.banner {
width: 100%;
height: 500px;
margin-top: 10px;
background-color: chocolate;
}
.bodyr {
width: 100%;
height: 800px;
margin-top: 10px;
background-color: #00a4ff;
}
.loos {
position: absolute;
right: 35px;
top: 200px;
width: 50px;
height: 100px;
background-color: chartreuse;
}
.loos span {
display: none;
}
xxxxxxxxxx
var loos = document.querySelector(".loos");
var banner = document.querySelector(".banner");
var bodyr = document.querySelector(".bodyr");
var span = loos.querySelector("span");
// banner 距离页面顶部的高度
var bannertop = banner.offsetTop;
// 返回块 停止的位置
var loostop = loos.offsetTop - bannertop;
// body 距离页面顶部的高度
var bodyrtop = bodyr.offsetTop;
// 页面滚动事件
document.addEventListener("scroll", function () {
if (window.pageYOffset >= bannertop) {
// 固定定位 是以 浏览器可视区域为参考的
// 绝对定位 是以 有定位的父元素 为参考的
loos.style.position = "fixed";
loos.style.top = loostop + "px";
} else {
loos.style.position = "absolute";
loos.style.top = "200px";
}
if (window.pageYOffset >= bodyrtop) {
span.style.display = "block";
} else {
span.style.display = "none";
}
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.