2个不同高度的DIV在滚动时达到顶部和底部相同的时间
我有2个DIV,它们总是不同的高度,因为内容会根据页面而变化。 我希望这两个不同高度的DIV在滚动时同时到达页面的顶部和底部。
这是我正在努力实现的一个工作示例 – http://jsfiddle.net/eBk5f/
问题是,当CONTENT DIV的内容少于CONTENT-SIDEBAR DIV并且没有在页面下方拉伸时,滚动条消失并且function丢失。
问题的例子在这里 – http://jsfiddle.net/nESaT/
无论DIV中的内容高度如何,如何保留工作示例的function?
编辑:更新的工作示例脚本与身体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; }
我希望代码是不言自明的。
这里出了什么问题, #content-sidebar
将它的位置设置为fixed,这意味着它已从文档布局中删除。
这意味着#content-sidebar
中的#content-sidebar
实际上不会影响body
的高度。 虽然body
内容不会填充body
的高度,但窗口不会滚动。
为了缓解这个问题,您可以简单地计算#content-sidebar
的高度,并设置它从屏幕顶部偏移的高度(如果您决定从顶部移动它)并将其设置为主体的高度,如果高于窗口的高度,将带回您已实现的溢出和滚动function。
这样的事情会做:
if($('#content-sidebar').height() > $('#content').height()) { $('body').css('height',$('#content-sidebar').offset().top+$('#content-sidebar').height()); }
例