使用getBoundingClientRect做一个简单的吸顶效果
getBoundingClientRect可以根据dom的四个边获得与window上边或左边的距离。
const obj = dom.getBoundingClientRect();
obj.top = dom的上边距离window上边的距离;
obj.bottom = dom的下边距离window上边的距离;
obj.left = dom的左边距离window左边的距离;
obj.right = dom的右边距离window左边的距离;
思路在于获取需要吸顶的dom的高度和该dom下方dom的top和bottom进行一个计算。代码如下。
1 <html lang="en"> 2 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>test</title> 7 <style> 8 9 body { 10 padding: 0; 11 margin: 0; 12 } 13 14 .top-container { 15 height: 21px; 16 width: 100%; 17 display: inline-block; 18 } 19 20 .top { 21 height: 21px; 22 background: #fff; 23 width: 100%; 24 } 25 26 .top-content, 27 .bottom-content { 28 height: 200vh; 29 display: inline-block; 30 width: 100%; 31 background-color: #f1f1f1; 32 } 33 </style> 34 </head> 35 36 <body> 37 <div class="top-content"></div> 38 <div class="top-container"> 39 <div class="top">top</div> 40 </div> 41 <div class="bottom-content"></div> 42 </body> 43 <script> 44 function fixedTop(element, option) { 45 this.element = element; 46 this.setting = Object.assign({}, fixedTop.defaults, option); 47 this.init(); 48 } 49 50 fixedTop.defaults = { 51 fixed: "position: fixed;top: 0;z-index: 1000", 52 none: "position: relative;z-index: 0", 53 }; 54 55 fixedTop.prototype = { 56 init: function () { 57 const element = this.element; 58 const { fixed, none, id } = this.setting; 59 window.addEventListener('scroll', () => { 60 const obj = document.getElementsByClassName(id)[0].getBoundingClientRect(); 61 if (obj.top - element.clientHeight < 0 && obj.bottom - element.clientHeight > 0) { 62 element.style = fixed; 63 } else { 64 element.style = none; 65 } 66 }); 67 } 68 } 69 fixedTop.constructor = fixedTop; 70 new fixedTop(document.querySelectorAll('.top-container')[0], { id: 'bottom-content' }); 71 </script> 72 73 </html> 74