需求:
1、页面滚动到距离顶部一定距离时,侧边浮窗从侧边出现
2、点击关闭按钮,再向上滑动,侧边浮窗不再出现,直到回到页面顶部
简单代码示例如下:
##HTML
<!-- 右侧浮窗 -->
<div class="Right">
<div class="right">
右侧浮窗
</div>
<div class="close">
X
</div>
</div>
##CSS
/* 右侧浮窗 */
.Right {
height: 150px;
width: 120px;
position: fixed;
top: 50%;
right: -120px;
margin-top: -75px;
font-size: 18px;
text-align: center;
background-color: pink;
transition: 1.0s;
}
.right {
line-height: 150px;
}
.close {
height: 25px;
line-height: 25px;
width: 25px;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
transition: .5s;
}
/* 旋转 */
.close:hover {
transform: rotate(180deg);
}
##JS
window.onload = function () {
//动画函数x
function animateX(floatSelector, distance) {
const floatElement = document.querySelector(floatSelector);
floatElement.style.transform = 'translateX(' + distance + 'px)';
}
//使用Isclose来标记
let Isclose = false;
// 监听页面滚动事件
window.addEventListener('scroll', function () {
// 获取页面滚动距离
const scrollTop = window.scrollY || document.documentElement.scrollTop;
// 判断滚动距离是否达到触发条件
if (scrollTop >= 200 && !Isclose) {
animateX('.Right', -120);
}
else {
animateX('.Right', 120);
}
});
//监听页面滚动到顶部事件
window.addEventListener("scroll", function () {
// 获取页面滚动距离
const scrollTop = window.scrollY || document.documentElement.scrollTop;
if (scrollTop == 0) {
Isclose = false;
}
})
//关闭侧边浮窗
const close = document.querySelector(".close");
close.addEventListener('click', function () {
animateX(".Right", 120);
Isclose = true;
})
}