如何同步两个div的滚动位置? [英] How do I synchronize the scroll position of two divs?

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

问题描述

我希望有两个大小为特定宽度的div(即500px)。一个在另一个上方水平对齐。

I want to have 2 divs sized to a particular width (i.e. 500px). One above the other aligned horizontally.

顶部框应隐藏其滚动条,底部应显示滚动条,当用户滚动时我想要偏移顶部框改为底部框的值。因此,当底部DIV水平滚动时,顶部DIV也会同时滚动。

The top box should hide its scroll bar, the bottom should show a scroll bar and when the user scrolls I'd like the offset of the top box to change to the value of the bottom box. So that when the bottom DIV scrolls horizontally it appears that the top DIV is also scrolling in unison.

我很高兴在Jquery中执行此操作,如果它使过程更容易。

I'm happy to do this in Jquery if it makes the process easier.

推荐答案

$('#bottom').on('scroll', function () {
    $('#top').scrollTop($(this).scrollTop());
});

这里我们使用 .scrollTop()为了它的价值,从带有滚动条的元素中获取 scrollTop 值,并为其他元素设置 scrollTop 要同步其滚动位置的元素: http://api.jquery.com/scrollTop

Here we are using .scrollTop() for all it's worth, getting the scrollTop value from the element with scroll-bars, and setting the scrollTop for the other element to sync their scroll positions: http://api.jquery.com/scrollTop

这假设您的底部元素的ID为 bottom ,并且您的top元素的ID为 top

This assumes that your bottom element has an ID of bottom and your top element has an ID of top.

您可以使用CSS隐藏 top 元素的滚动条:

You can hide the scroll-bars for the top element using CSS:

#top {
    overflow : hidden;
}

这是一个演示: http://jsfiddle.net/sgcer/1884/

我想我从来没有真的有理由这样做,但它看起来很酷。

I suppose I've never really had a reason to do this, but it looks pretty cool in action.

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

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