萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> 利用jquery的滾動條滾動固定div

利用jquery的滾動條滾動固定div

 js & jquery

<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var loaded = true;
var top = $("#demo").offset().top;
function Add_Data()
{
var scrolla=$(window).scrollTop();

//alert(top)


var cha=parseInt(top)-parseInt( scrolla);

alert(top+"-"+scrolla +"="+cha);


if(loaded && cha<=0)
{
$("#demo").removeClass("demo2").addClass("demo1");
$("#demo").html("我現在是藍色,把滾動條往上拉我會顯示成紅色。我已經固定了。");
loaded=false;
}
if(!loaded && cha>0)
{
$("#demo").removeClass("demo1").addClass("demo2");
$("#demo").html("我現在是紅色,把滾動條往下拉我會顯示成藍色。我還沒固定了。");
loaded=true;
}
}
$(window).scroll(Add_Data);
});
</script>

樣式表

<style type="text/css">
.demo
{
border: 1px solid #dcdcdc;
width: 300px;
margin-top: 10px;
overflow: auto;
text-align: left;
background-color: #ffffff;
height:200px;
}
.demo1
{
position: fixed;
_position: absolute;
top: 0px;
background-color: #0000ff;
height:200px;
width:300px;
color:#ffffff;
}
.demo2
{
border: 1px solid #dcdcdc;
width: 300px;
margin-top: 10px;
overflow: auto;
text-align: left;
background-color: #ff0000;
height:200px;
color:#ffffff;
}
</style>

html

<div class="demo">
1
</div>
<div class="demo">
2
</div>
<div class="demo">
3
</div>
<div class="demo">
4
</div>
<div class="demo2" id="demo">
我現在是紅色,把滾動條往下啦我會顯示成藍色。我還沒固定了。
</div>
<div class="demo">
6
</div>
<div class="demo">
7
</div>
<div class="demo">
8
</div>
<div class="demo">
9
</div>
<div class="demo">
10
</div>

copyright © 萬盛學電腦網 all rights reserved