我有 2 个始终具有不同高度的 DIV,因为内容会根据页面而变化。我希望这 2 个不同高度的 DIV 在滚动时同时到达页面的顶部和底部。
这是我正在努力实现的工作示例 - http://jsfiddle.net/eBk5f/
问题是,当 CONTENT DIV 的内容少于 CONTENT-SIDEBAR DIV 并且没有延伸到页面下方时,滚动条消失并且功能丢失。
此处的问题示例 - http://jsfiddle.net/nESaT/
无论两个 DIV 中内容的高度如何,如何保持工作示例的功能?
编辑:更新了带有主体 CSS 的工作示例脚本 - http://jsfiddle.net/TAyXD/
脚本:
$(document).ready(function(){
var doc = $(window);
$(window).bind('resize', function() {
$("#content-sidebar").css('top', (calculateScrollSpeed()));
});
$(window).bind('scroll', function() {
$("#content-sidebar").css('top', (calculateScrollSpeed()));
});
function calculateScrollSpeed() {
var leftPaneHeight = $('#content').height();
var rightPaneHeight = $('#content-sidebar').height();
var browserHeight = $(window).height();
var leftPaneScrollTop = $(window).scrollTop();
console.log((browserHeight - rightPaneHeight) / (browserHeight - leftPaneHeight));
return -$(window).scrollTop() * ((browserHeight - rightPaneHeight) / (browserHeight - leftPaneHeight));
}
});
最佳答案
这是一个可行的解决方案!
jQuery:
$(document).ready(function () {
var contentHeight = $('#content').height();
var sidebarHeight = $('#content-sidebar').height();
function setup(leftPaneHeight, rightPaneHeight) {
if (leftPaneHeight > rightPaneHeight) {
$("#content-sidebar").css('position', 'fixed');
} else {
$("#content").css('position', 'fixed');
}
}
function calculate(leftPaneHeight, rightPaneHeight) {
var browserHeight = $(window).height();
var scrollerPosition = $(window).scrollTop();
if (leftPaneHeight > rightPaneHeight) {
var result = (-scrollerPosition * ((browserHeight - rightPaneHeight) / (browserHeight - leftPaneHeight)));
return $("#content-sidebar").css('top', result + 'px');
} else {
var result = (-scrollerPosition * ((browserHeight - leftPaneHeight) / (browserHeight - rightPaneHeight)));
return $("#content").css('top', result + 'px');
}
}
$(window).bind('resize', function () {
calculate(contentHeight, sidebarHeight);
});
$(window).bind('scroll', function () {
calculate(contentHeight, sidebarHeight);
});
setup(contentHeight, sidebarHeight);
});
CSS:
#content {
float: left;
position: relative;
width: 400px;
}
#content-sidebar {
float: left;
position: relative;
margin-left: 400px;
width: 400px;
}
我希望代码是不言自明的。
关于javascript - 2 个不同高度的 DIV 在滚动条上同时到达顶部和底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24602783/