<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{margin:0;padding:0;} .Suction_cap{width:100%;height:100px;overflow:hidden;background:skyblue;} .main{width:1200px;height:1500px;} </style> </head> <body> <div class="box"> <div id="Suction_cap" class="Suction_cap"> 头部 </div> <div class="main"> 测试<br/> 测试<br/> 测试<br/> 测试<br/> 测试<br/> </div> </div> <script> function Suction_cap(obj){ this.ele=document.getElementById(obj)||document.getElementsByClassName(obj)[0]; this.height=this.ele.offsetHeight; this.copy=document.createElement(‘div‘); this.parent_ele=this.ele.parentNode; var _this=this; window.onscroll=function(){ var scrollT = document.documentElement.scrollTop || document.body.scrollTop; if(scrollT>0){ _this.insertAfter( _this.copy, _this.ele); _this.copy.style.height=_this.getStyle(_this.ele,‘height‘); _this.copy.style.display=‘block‘; _this.ele.style.position=‘fixed‘; _this.ele.style.boxShadow="0 0 5px #888"; }else{ _this.parent_ele.removeChild(_this.copy); _this.ele.style.display=‘block‘; _this.ele.style.position=‘relative‘; _this.ele.style.boxShadow="0 0 0 #fff"; } } } Suction_cap.prototype.getStyle=function(obj,attr){ if(obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } } Suction_cap.prototype.insertAfter=function( newElement, targetElement){ var parent = targetElement.parentNode; if ( parent.lastChild == targetElement ) { parent.a( newElement ); } else { parent.insertBefore( newElement, targetElement.nextSibling ); } } var obj=new Suction_cap(‘Suction_cap‘); </script> </body> </html>
时间: 2024-10-24 05:31:32