JavaScript 实现侧边栏滚动特效:右边文章可见区域高度 oarticleH 大于左边侧边栏可见区域高度 osidebarH 时触发 scrollEvent 事件。如果网页被卷去的高度 scrollH 加上屏幕可视化区域高度 screenH 大于左边侧边栏可见区域高度 osidebarH ,左边侧边栏 osidebar 固定(属性 position 的属性值置为 fixed),若滚动到右边文章底部,左边侧边栏 osidebar 不固定(属性 position 的属性值置为 absolute)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <title>JavaScript实现侧边栏滚动特效</title> <meta name="viewport" content="width=1024"> <meta name="author" content="双鱼bizhongbio, http://www.bizhongbio.com/"> <style> *{padding: 0;margin: 0;} body{font: 16px/1 'Microsoft YaHei',Arial,Helvetica,sans-serif;background: #e9eaec;} .header{position: relative;z-index: 999;width: 100%;height: 55px;background: #fff;border-bottom: 1px solid #d7d7d7;} #main{position: relative;width: 1024px;margin: 35px auto;} #article{position: relative;height: 2000px;margin-left: 350px;background: #fff;} #sidebar{position: absolute;top: 0;width: 315px;height: 1000px;background: #fff;} #footer{background: #f2f2f2;width: 100%;height: 369px;} </style> </head> <body> <header class="header"></header> <div id="main"> <article id="article"></article> <aside id="sidebar"></aside> </div> <footer id="footer"></footer> <script> window.onload = function(){ var $ = function(id){ return document.getElementById(id); }; var screenH = document.documentElement.clientHeight || document.body.clientHeight; var addEvent = function(obj,event,fn){ if(obj.addEventListener){ obj.addEventListener(event,fn,false); }else if(obj.attachEvent){ obj.attachEvent('on'+event,fn); } }; var scrollEvent = function(){ var scrollH = document.documentElement.scrollTop || document.body.scrollTop, obodyH = document.body.scrollHeight,// 网页正文全文高 omainH = $("main").offsetHeight, oarticleH = $("article").offsetHeight, osidebar = $("sidebar"), osidebarH = osidebar.offsetHeight, ofooterH = $("footer").offsetHeight; if(oarticleH > osidebarH){// 右边文章主体高度大于左边侧边栏高度 if(scrollH + screenH > osidebarH){ osidebar.style.cssText = "position:fixed;top:" + (-(osidebarH-screenH)) + "px;"; if(scrollH >= obodyH - ofooterH - screenH - 35){// 35是类main的margin-bottom的属性值 osidebar.style.cssText = "position:absolute;top:auto;bottom:0px;"; } }else{ osidebar.style.cssText = "position:absolute;top:0px;"; } } }; addEvent(window,'scroll',function(){// 当执行滚动时触发scrollEvent事件 scrollEvent(); }); addEvent(window,'resize',function(){// 当resize时触发scrollEvent事件 scrollEvent(); }); }; </script> </body> </html> |
暂无评论
还没有任何评论,你来说两句吧。