好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

js实现淘宝固定侧边栏

本文实例为大家分享了js实现淘宝固定侧边栏的具体代码,供大家参考,具体内容如下

1.实现效果:

当页面运行到banner区域时,右边侧边栏改为固定定位,当页面运行到主体区域时,右边侧边栏显示返回到顶部。

2.思路:

(1)给document加scroll事件。

(2)获取页面被卷去的部分用window.pageYOffset.

(3)不断判断页面滚动了多少。计算右边侧边栏应该待的位置。

3.代码:

pink老师用了固定定位fixed(固定定位是相对于窗口的距离),我做的还是用绝对定位(绝对定位是相对于父元素来说的,即document),都是可以实现的。

<!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>
? ? <style>
? ? ? ? .top {
? ? ? ? ? ? width: 80%;
? ? ? ? ? ? height: 200px;
? ? ? ? ? ? background-color: pink;
? ? ? ? }
? ? ? ? .banner {
? ? ? ? ? ? width: 80%;
? ? ? ? ? ? height: 400px;
? ? ? ? ? ? background-color: aquamarine;
? ? ? ? }
? ? ? ? .main {
? ? ? ? ? ? width: 80%;
? ? ? ? ? ? height: 800px;
? ? ? ? ? ? background-color: red;
? ? ? ? }
? ? ? ? .foot {
? ? ? ? ? ? width: 80%;
? ? ? ? ? ? height: 400px;
? ? ? ? ? ? background-color:blanchedalmond;
? ? ? ? }
? ? ? ? .lan {
? ? ? ? ? ? position: absolute;
? ? ? ? ? ? right:10%;
? ? ? ? ? ? top:400px;
? ? ? ? ? ? width: 80px;
? ? ? ? ? ? height: 80px;
? ? ? ? ? ? background-color: cadetblue;
? ? ? ? }
? ? </style>
</head>
<body>
? ? <div class="top">头部区域</div>
? ? <div class="banner">banner区域</div>
? ? <div class="main">头部区域</div>
? ? <div class="foot">尾部区域</div>
? ? <div class="lan"></div>
? ? <script>
? ? ? ? var lan = document.querySelector('.lan');
? ? ? ? document.addEventListener('scroll', function() {
? ? ? ? ? ? console.log('jkjkkj');
? ? ? ? ? ? var top = window.pageYOffset;
? ? ? ? ? ? if(top ?> 200) {
? ? ? ? ? ? ? ? // 改为固定定位。
? ? ? ? ? ? ? ? var topp = 400-200 + top;
? ? ? ? ? ? ? ? lan.style.top = topp+'px';
? ? ? ? ? ? ? ? if(top > 600) {
? ? ? ? ? ? ? ? ? ? lan.innerHTML = '返回顶部';
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? lan.innerHTML = '';
? ? ? ? ? ? ? ? }
?
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? lan.style.top = 400+'px';
? ? ? ? ? ? ? ? lan.innerHTML = '';
? ? ? ? ? ? }
? ? ? ? })
? ? </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于js实现淘宝固定侧边栏的详细内容...

  阅读:30次