"sticky sidebar" ก็คือการทำแถบ sidebar ให้คงทีตลอด เมื่อเราเลื่อน Scroll เเถบนี้ก็จะคงทีไม่หายไปใหน ถ้ายังนึกไม่ออกเรามีภาพตัวอย่างมาให้ดูค่ะ สังเกตุว่าเมื่อเราเลื่อนเมาส์ลงมาเเถบ sidebar ก็จะตามมาด้วย ซึ่งเกือบทุกเว็บไซต์ จะมีพื้นที่เนื้อหาหลัก(content)และ แถบด้านข้าง(sidebar) แสดง สิ่งดีๆ เพิ่มเติม และเกือบจะตลอดเวลาที่ความสูงของ แถบด้านข้าง จะมีขนาดเล็ก กว่าเนื้อหาหลัก(content) ที่นี่ถ้าเราทำการเลื่อน Scroll ลงมาเเล้วต้องการที่จะให้ แถบด้านข้าง(sidebar) ยังคงทีตามเนื้อหาหลักเราจะทำได้โดยขั้นตอนดังนี้ค่ะ
ในตัวอย่างนี้จะมีโครงสร้างไฟล์ดังนี้ค่ะ ไฟล์ styles.css กำหนดเนื้อหาเเละขนาดของกรอบ ต่างๆ
[code]body {
margin: 0;
padding: 0;
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
font-size: 10pt;
line-height: 150%;
border-top: 8px solid #106870;
}
.contentBox {
max-width: 1000px;
margin: 30px auto 0 auto;
}
.contentLeft {
width: 670px;
float: left;
text-align: justify;
}
.sidebarBox {
width: 300px;
float: right;
position: relative;
}
.scrollingBox {
width: 300px;
}
[/code]
ไฟล์ Index.html ให้เราทำการวางโครงสร้างของเว็บเพจค่ะ ดังตัวอย่าง
[code]<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title></title>
<link rel="stylesheet" href="styles.css" />
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="contentBox">
<div class="contentLeft">
<h1>Content</h1>
<img src="img/content.png" alt=""></img>
<br></br>
<img src="img/content_1.png"></img>
<br></br>
<img src="img/content_2.png"></img>
<br></br>
<img src="img/content_3.png"></img>
</div>
<div class="sidebarBox">
<h3>Search</h3>
<p><input type="text" /> <input type="submit" value="Go" /></p>
<br />
<div class="scrollingBox">
<h3>Sidebar Images</h3>
<img src="img/Sidebar.png"></img>
</div>
<br />
<h3>บทความล่าสุด</h3>
<ul>
<li>
บทความที่ 1
</li>
<li>
บทความที่ 2
</li>
<li>
บทความที่ 3
</li>
<li>
บทความที่ 4
</li>
<li>
บทความที่ 5
</li>
<li>
บทความที่ 6
</li>
</ul>
</div>
</div>
</body>
</html>[/code]
คำอธิบาย : จะเห็นว่ามีการเรียกใช้งาน CSS เเละ JavaScript libraries (จะมีอยู่ในตัวอย่างสามารถดาวน์โหลดได้ค่ะ)
โค้ด: เลือกทั้งหมด
<link rel="stylesheet" href="styles.css" />
<script src="jquery-1.11.0.min.js"></script>
[code]<script type="text/javascript">
$(function() {
var offsetPixels = 600; // ขนาดของ scroll ความสูงเมื่อเราเลื่อนเมาส์ เเล้วจะให้ขนาดเท่ากับ 600 เเล้วจึงค้าง
$(window).scroll(function() {
if ($(window).scrollTop() > offsetPixels) { // เมื่อทำการ scroll ลงมากกว่าที่เรากำหนดไว้
// ในส่วนนี้จะทำเมื่อเรา scroll down ลงมา
$(".scrollingBox").css({ // ใน class scrollingBox ให้กำหนด คุณสมบัติเพิ่มเข้าไป ตรงนี้เเหละค่ะ ที่จะเป็นส่วนว่าเราจะเอาส่วนใหนว่าทำให้ คงที
"position": "fixed",
"top": "15px"
});
} else { // ในส่วนนี้จะทำเมื่อเรา scroll up กลับไปด้านบน
$(".scrollingBox").css({
"position": "relative",
"top": "0"
});
}
});
});
</script>[/code]
จากนั้นดูผลได้เลยค่ะ[/color]
สามารถดาวน์โหลด code ตัวอย่างได้ที่นี่ค่ะ