Cái bạn muốn làm, chỉ cần tìm google từ khóa "
jQuery Sticky Scroll Plugins".
Còn với cái bạn đang làm thì bạn không đưa demo trang của bạn nên mình không rõ ảnh hường của các thành phần liên quan hay có bị xung đột với script khác không. Vì thế mình viết lại với cách dùng tương tự
(Lưu ý cấu trúc HTML và CSS).
Demo
http://jsfiddle.net/baivong/jwc6kruj/embedded/result,js,html,css/
Source
HTML
- Code:
<div id="header">#header</div>
<div id="main">
<div id="widget">
<div id="sticky">#sticky</div>
</div>
<div id="content">#content</div>
</div>
<div id="footer">#footer</div>
CSS
- Code:
* {
padding: 0;
margin: 0;
}
body {
color: #FFF;
}
#header {
height: 100px;
background: black;
}
#main {
width: 400px;
background: green;
margin: 0 auto;
}
#main:after {
content:"";
display:table;
clear:both;
}
#widget {
width: 100px;
position: relative;
float: left;
height: 300px;
}
#content {
background: blue;
width: 300px;
float: left;
height: 1500px;
}
#footer {
background: black;
height: 200px;
}
#sticky {
width: 100px;
height: 200px;
background: orange;
}
Javascript
- Code:
var stickyHeight = 200, // chiều cao của banner quảng cáo
padding = 0, // khoảng cách top của banner khi dính
topOffset = 100, // khoảng cách từ top của banner khi bắt đầu dính (tức là khoảng cách tính từ trên xuống đến vị trí đặt banner )
footerHeight = 200, // Định vị điểm dừng của banner, tính từ chân lên
$win = $(window),
$sticky = $("#sticky"),
docHeight = $(document).height(),
winHeight = $win.height(),
noSTheight = stickyHeight + padding + footerHeight;
function scrollSticky() {
var scrollTop = $win.scrollTop(),
cssTop, cssPosition;
if (winHeight >= stickyHeight && scrollTop >= topOffset) {
if (noSTheight + scrollTop < docHeight) {
cssTop = padding;
cssPosition = "fixed";
} else {
cssTop = docHeight - noSTheight - topOffset;
cssPosition = "absolute";
}
} else {
cssTop = 0;
cssPosition = "relative";
}
$sticky.css({
position: cssPosition,
top: cssTop
});
}
$win.resize(function () {
winHeight = $win.height();
}).scroll(function () {
scrollSticky();
});