html 屏幕滚动监听,显示窗口的数据改变.
2018年8月30日实现原理
想要实现这个功能,就要知道具体的实现原理。下面直入主题。 我们通过浏览器在浏览一个网页时候是这个样子的,如图所示
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 68 69 70 71 72 73 74 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <style type="text/css"> .box { width: 100%; height: 200px; background: #ff0000; margin-bottom: 10px; text-align: center; color: #fff; line-height: 200px; font-family: microsoft yahei; font-size: 40px; } .animate { animation: showText 1s; } @keyframes showText { from { font-size: 20px; } to { font-size: 40px; } } </style> <body> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> </body> <script type="text/javascript"> var box = document.getElementsByClassName('box'); document.addEventListener('scroll', function () { //监听整个屏幕的滚动事件 var visibleBottom = window.scrollY + document.documentElement.clientHeight; //滚动条高度+视窗高度 = 可见区域底部(那条线)高度 var visibleTop = window.scrollY; //可见区域顶部高度顶部那条线() 可以理解为上边距 for (var i = 0; i < box.length; i++) { var centerY = box[i].offsetTop + (box[i].offsetHeight / 2); //获取这个元素的上边距,和高度/2就是中间线 if (centerY > visibleTop && centerY < visibleBottom) { //这个数必须在这两个数中间 box[i].innerHTML = '区域可见' //插入html box[i].setAttribute("class", 'box animate') //插入属性 console.log('第' + i + '个区域可见'); //打印 } else { box[i].innerHTML = ''; //插入html box[i].setAttribute("class", 'box') //插入属性 console.log('第' + i + '个区域不可见'); //打印 } } } ) </script> </html> |