ตัวอย่างโค้ดต่อไปนี้ เป็นแนวทางสำหรับการสร้างส่วนของเนื้อหาให้สามารถ fixed ตำแหน่ง
เมื่อมีการเลื่อน scrollbar ของหน้าเพจนั้น ถึงตำแหน่งที่เรากำหนด และ ส่วนของเนื้อหานั้น
จะกลับมาอยู่ตำแหน่งเดิม เมื่อการเลื่อน scrollbar หน้าเพจนั้น ไม่เข้าเงื่อนไข
โค้ดทั้งหมด ดูตัวอย่าง ได้จากล๊งค์ด้านล่าง
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>fixed position when scroll</title>
<style type="text/css">
html,body{
background-color:#CCC;
padding:0px;
margin:0px;
}
div.main_test{
position:relative;
background-color:#999;
margin:auto;
width:800px;
}
div.top_sector{
position:relative;
display:block;
width:100%;
height:75px;
background-color:#036;
color:#FFF;
}
/* css ส่วนของเนื้อหาที่ต้องการในตรึง เมื่อเลือน scroll ถึงตำแหน่งที่ต้องการ */
div.my_float_div{
position:relative;
display:block;
width:250px;
height:160px;
background-color:#DCDCF5;
color:#000;
padding:5px;
}
</style>
</head>
<body>
<div class="main_test">
<div class="top_sector">Top Sector</div>
<br />
<?php
// php สร้างบรรทัดใหม่ สำหรับทดสอบ
for($i=1;$i<=10;$i++){ ?>
<?=$i?>.<br />
<?php } ?>
<div class="my_float_div">
Data Content 1<br />
Data Content 1<br />
Data Content 1<br />
Data Content 1<br />
Data Content 1<br />
Data Content 1<br />
Data Content 1<br />
</div>
<?php
// php สร้างบรรทัดใหม่ สำหรับทดสอบ
for($i=11;$i<=100;$i++){ ?>
<?=$i?>.<br />
<?php } ?>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
// เงื่อนไข event เมื่อมีการเลื่อน scrollbar ในหน้าเพจ
$(window).scroll(function(){
// เมื่อเลื่อน scroll bar หน้าเพจ ถึงตำแหน่งที่มากกว่าหรือเท่ากับตำแหน่งที่ต้องการ
// เมื่อเลื่อน scroll bar หน้าเพจ ถึงตำแหน่ง ที่ทำให้ div
// class ชื่อ my_float_div ชิดขอบบนพอดี หาจากคำสั่ง
// console.log($(document).scrollTop());
if($(document).scrollTop()>270){
$(".my_float_div").css({ /* */
'position':'fixed',
'top':'0px'
});
}else{ // เลื่อนกลับมาอยู่ตำแหน่งเดิม ถ้าไม่อยู่ในเงื่อนไข
$(".my_float_div").css({
'position':'relative'
});
}
});
});
</script>
</body>
</html>