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

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

问题描述

我正在尝试使用以下代码为两个 DIV 实现同步滚动.

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

演示

$(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) 来获取百分比(它将是一个01 之间的值).因此,您可以将其他元素的 (.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/

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

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