12

I have two DIV elements #page and #block :

<div id="page"></div>
<div id="block"></div>

#block element has fixed position and long content inside with overflow:hidden property.

#page element has some content inside too, but it height of #page will be longer or shorter then #block height.

My goal is to achieve synchronized scroll between this two elements. Something like this:

enter image description here

I need to calculate speed of #block element scroll, because header and footer elements of #page and #block should be at same position from beginning and at the end of scroll.

The way I tried to achieve this:

  • Calculated height of #page element
  • Calculated height of #block element content (because block element is fixed and has alwas fixed height)
  • Calculated #block element scroll speed by:

    $("#block").outerHeight / $("#page").outerHeight

  • Triggered .scrollTop() of #block

It's working from the beginning and #block element scroll is faster then #page element scroll, but at the end, #block is not scrolled fully.

Here is my JsFiddle: http://jsfiddle.net/zur4ik/bQYrf/2/

Maybe anyone can see what I'm doing wrong?

Thanks in advance.

4

3 回答 3

10

您必须将其window height纳入案例并将其从元素高度中减去。

$(window).scroll(function() {
    var pageH = $('#page').height() - $(this).height();
    var pageT = this.scrollY - $('#page').offset().top;

    $('#block').scrollTop(pageT / pageH * ($('#blockLength').height() - $(this).height()));
});

这是更新的小提琴:http: //jsfiddle.net/bQYrf/4/

于 2013-11-05T10:15:14.967 回答
3

我发现在 SO 中已经回答了同一个问题的两个例子:

如果我正确理解您的问题,这正是您要寻找的: 使用 jQuery 进行同步滚动?

这也是一个很好的解决方案: 如何同步两个div的滚动位置?

于 2013-11-05T10:11:13.793 回答
1
function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

var clientHeight = getClientHeight();

$(window).scroll(function() {

    var diff = ($("#blockLength").height() - clientHeight) / ($("#page").height() - clientHeight);
    var blocktoSet = $(window).scrollTop() * diff;

    $("#block").scrollTop(blocktoSet);

    console.log()



});

http://jsfiddle.net/PeGky/1/

于 2013-11-05T10:14:49.530 回答