1、通过js实现侧边栏的固定效果,滑轮的上下滑动可以控制侧边栏的定位是固定的还是绝对的。
2、话不多说直接上源码(没有注释需要解释私信)。
可以直接复制粘贴查看效果
<!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>仿淘宝的固定侧边栏案例</title>
<style>
* {
margin: 0;
padding: 0;
}
header {
height: 200px;
width: 1400px;
background-color: blue;
margin: 0 auto;
}
.main_web {
position: relative;
width: 1400px;
height: 1000px;
background-color: #333;
margin: 0 auto;
}
.side_box {
position: absolute;
top: 300px;
right: 10px;
height: 100px;
width: 50px;
background-color: black;
color: #fff;
}
#ddd {
display: none;
}
footer {
width: 1400px;
height: 1000px;
background-color: #ccc;
margin: 0 auto;
}
</style>
</head>
<body>
<header></header>
<div class="side_box">
<span id="ddd">顶部</span>
</div>
<div class="main_web">
</div>
<footer></footer>
<script>
var sideBox = document.querySelector('.side_box');
var header = document.querySelector('header');
var mainWeb = document.querySelector('.main_web');
var footer = document.querySelector('footer');
var ddd = document.querySelector('#ddd');
var dd = sideBox.offsetTop - mainWeb.offsetTop;
window.addEventListener('scroll', function () {
if (window.pageYOffset >= header.offsetHeight) {
sideBox.style.position = 'fixed';
sideBox.style.top = dd + 'px';
}
else {
sideBox.style.position = 'absolute';
sideBox.style.top = 300 + 'px';
}
if (window.pageYOffset >= footer.offsetTop) {
ddd.style.display = 'block';
}
else {
ddd.style.display = 'none';
}
})
</script>
</body>
</html>