问题描述
我找不到一种方法来同步两个div,它们具有相同的文本,但是具有不同的文本大小和填充.我有两个div,一个带有markdown文本,另一个带有markdown的html渲染,我想在div之间同步scrollTop
.
I can't find a way to synchronize two divs, with the same text, but different text size and padding.I have two divs, one with a markdown text, and the other one with the html render of the markdown and I want to synchronize the scrollTop
between the divs.
例如,查看 stackedit.io
推荐答案
您可以在以下位置看到同步两个div的示例: JSFiddle
You can see the example of synchronizing two divs at: JSFiddle
HTML
鉴于您将两个div水平相邻放置.每个div都包含另一个div,并且可以垂直滚动:
Given you have two divs placed next to each other horizontally. Each of the divs contain another div and it is scrollable vertically:
<div class="outer" id="div1">
<div>
</div>
</div>
<div class="outer" id="div2">
<div>
</div>
</div>
CSS
这只是使两个外部div在同一基线处彼此相邻并使其垂直滚动.
This is just to make two outer divs lie next to each other at the same baseline and make it scrollable vertically.
div.outer
{
display:inline-block;
width:150px;
height:320px;
border:1px solid black;
overflow-y:auto;
}
div.outer > div
{
width:100%;
height:3000px;
}
JavaScript
最简单的方法是将scroll
事件绑定到每个外部div,采用scrollTop
值并将其应用于对应的div,如下所示:
The simplest approach is, bind scroll
event to each of the outer divs, take the scrollTop
value and apply to its counterpart div as follows:
$('#div1').scroll(function(){
$('#div2').scrollTop( $('#div1').scrollTop() );
});
$('#div2').scroll(function(){
$('#div1').scrollTop( $('#div2').scrollTop() );
});
因此,当您在左侧div上滚动时,它会同步右侧div,反之亦然.
So when you scroll on the left div, it synchronizes the right div, and vice-versa.
这篇关于在具有不同文本大小的2个div之间同步滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!