1. 程式人生 > >js應用例子——滾動固定

js應用例子——滾動固定

post text pad log cti olly 監聽 element posit


<style type="text/css">

*{ margin:0px auto; padding:0px;}
#wai{ width:100%; height:3000px;}
#head{ width:100%; height:200px; background-color:#C30;}
#dhl{ width:100%; height:150px; background-color:#00C;}
#neirong{ width:100%; height:2000px;}
.a{ width:100px; height:200px; background-color:#0FF; margin-top:30px;}
</style>

<div id="wai">
<div id="head"></div>
<div id="dhl"></div>
<div id="neirong">
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
<div class="a"></div>
</div>
</div>

<script>

//這裏用到的window.onscroll 是網頁滾動監聽, scrollY是網頁下拉是滾動的長度,用alert輸出是不帶px的數值;


window.onscroll = function(){
if(window.scrollY>200){
  var dhl = document.getElementById("dhl");
  dhl.style.position = "fixed";
  dhl.style.top = "0px";
  } else{
  dhl.style.position="";
}
}
</script>

js應用例子——滾動固定