使用jQuery的同步滚动? [英] Synchronized scrolling using jQuery?

查看:142
本文介绍了使用jQuery的同步滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用下面的代码实现两个 DIV 的同步滚动。

I am trying to implement synchronized scrolling for two DIV with the following code.

DEMO

$(document).ready(function() {
    $("#div1").scroll(function () { 
        $("#div2").scrollTop($("#div1").scrollTop());
    });
    $("#div2").scroll(function () { 
        $("#div1").scrollTop($("#div2").scrollTop());
    });
});

#div1 #div2 具有相同的内容,但大小不同,例如

#div1 and #div2 is having the very same content but different sizes, say

#div1 {
 height : 800px;
 width: 600px;
}
#div1 {
 height : 400px;
 width: 200px;
}

使用此代码,我面临两个问题。

With this code, I am facing two issues.

1)滚动不同步,因为div是不同的大小。我知道,这是因为,我直接设置 scrollTop 值。我需要找到滚动内容的百分比,并为其他 div 计算相应的 scrollTop 值。我不知道,如何找到实际的高度和当前的滚动位置。

1) Scrolling is not well synchronized, since the divs are of different sizes. I know, this is because, I am directly setting the scrollTop value. I need to find the percentage of scrolled content and calculate corresponding scrollTop value for the other div. I am not sure, how to find the actual height and current scroll position.

2)这个问题只能在 firefox 。在Firefox中,滚动不像在其他浏览器中那样流畅。我认为这是因为上面的代码是创建一个无限循环的滚动事件。
我不知道,为什么这只是发生在firefox。有任何方法可以找到滚动事件的来源,所以我可以解决这个问题。

2) This issue is only found in firefox. In firefox, scrolling is not smooth as in other browsers. I think this because the above code is creating a infinite loop of scroll events. I am not sure, why this is only happening with firefox. Is there any way to find the source of scroll event, so that I can resolve this issue.

任何帮助将非常感激。

推荐答案

您可以使用 element.scrollTop /(element.scrollHeight - element.offsetHeight) (它将是 0 1 之间的值)。因此,您可以将其他元素的(。scrollHeight --.offsetHeight)乘以此值进行比例滚动。

You can use element.scrollTop / (element.scrollHeight - element.offsetHeight) to get the percentage (it'll be a value between 0 and 1). So you can multiply the other element's (.scrollHeight - .offsetHeight) by this value for proportional scrolling.

避免在循环中触发侦听器,您可以临时解除绑定侦听器,设置 scrollTop 并重新重新绑定。

To avoid triggering the listeners in a loop you could temporarily unbind the listener, set the scrollTop and rebind again.

var $divs = $('#div1, #div2');
var sync = function(e){
    var $other = $divs.not(this).off('scroll'), other = $other.get(0);
    var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
    // Firefox workaround. Rebinding without delay isn't enough.
    setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on( 'scroll', sync);

http://jsfiddle.net/b75KZ/5/

http://jsfiddle.net/b75KZ/5/

这篇关于使用jQuery的同步滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆