jQuery在滚动时固定侧栏,直到底部 [英] jquery fixing a side bar while scrolling, until bottom
问题描述
此代码取自waypointarts.com,假设在滚动时创建固定边栏,直到底部. 问题是当右div填充左div的高度时,即使将其设置为100#仍固定为某个高度,窗口/屏幕或其他东西.我如何设置它的高度为100%或等于正确的div高度.
This code is taken from waypointarts.com and it's suppose to create a Fixing a side bar while scrolling, until bottom. problem is when right div is populated the left div's height even though set to 100# stay fixed to certain height, window/screen or something. how can I set it so its 100% height or equivalent to right div's height.
HTML 标头
HTML Header
<div id="wrapper">
<div id="left">
<div id="sidebar">
Sidebar Content
</div>
</div>
<div id="right">
This is the text of the main part of the page.
</div>
<div class="clear"></div>
</div>
<div id="footer">Footer</div>
CSS
#header {
background: #c2c2c2;
height: 50px
}
#wrapper {
width: 500px
}
#left {
background: #d7d7d7;
position: absolute; /* IMPORTANT! */
width: 150px;
height: 100%
}
#right {
position: relative;
width: 350px;
float: right
}
#sidebar {
background: #0096d7;
width: 150px;
color: #fff
}
.clear {
clear: both
}
#footer {
background: #c2c2c2
}
JAVASCRIPT
JAVASCRIPT
$(document).ready(function () {
var length = $('#left').height() - $('#sidebar').height() + $('#left').offset().top;
$(window).scroll(function () {
var scroll = $(this).scrollTop();
var height = $('#sidebar').height() + 'px';
if (scroll < $('#left').offset().top) {
$('#sidebar').css({
'position': 'absolute',
'top': '0'
});
} else if (scroll > length) {
$('#sidebar').css({
'position': 'absolute',
'bottom': '0',
'top': 'auto'
});
} else {
$('#sidebar').css({
'position': 'fixed',
'top': '0',
'height': height
});
}
});
});
来自waypoitsarts.com的图片:
Image from waypoitsarts.com:
推荐答案
我认为您的脚本运行良好,可能是CSS出现了问题.为了正确地包含一个position:absolute;
元素,您应该将其父元素('#wrapper'
)设置为position:relative
.
I think your script is working fine, probably the problem is on your CSS. In order to properly contain a position:absolute;
element you should set its parent element ('#wrapper'
) to position:relative
.
有关此jsfiddle的演示,请参见: jsfiddle.net/J62Cp/
See the demo on this jsfiddle: jsfiddle.net/J62Cp/
这篇关于jQuery在滚动时固定侧栏,直到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!