jquery 如何同步两个div的滚动位置?

b5lpy0ml  于 2023-04-05  发布在  jQuery
关注(0)|答案(8)|浏览(192)

我想有两个div大小为一个特定的宽度(即500px)。一个在另一个上面水平对齐。
顶部框应该隐藏其滚动条,底部应该显示滚动条,当用户滚动时,我希望顶部框的偏移量更改为底部框的值。因此,当底部DIV水平滚动时,顶部DIV似乎也在同步滚动。
我很乐意在Jquery中这样做,如果它使这个过程更容易的话。

uubf1zoe

uubf1zoe1#

感谢上面的答案,我做了一个混合的解决方案,优先为我工作:

var isLeftScrollTopCalled = false;
$('#leftElement').scroll(function (e) {
    if (isRightScrollTopCalled) {
        return isRightScrollTopCalled = false;
    }

    $('#rightElement').scrollTop($(this).scrollTop());
    isLeftScrollTopCalled = true;
});

var isRightScrollTopCalled = false;
$('#rightElement').scroll(function (e) {
    if (isLeftScrollTopCalled) {
        return isLeftScrollTopCalled = false;
    }

    $('#leftElement').scrollTop($(this).scrollTop());
    isRightScrollTopCalled = true;
});
lrl1mhuk

lrl1mhuk2#

我注意到他的问题很老了,但我想我可以留下一个比使用计时器更好的jQuery实现。在这里,我使用了两个事件侦听器,就像以前使用的解决方案一样,但是,这将使用比例/百分比来同步两个不同大小的div框的滚动条。2你可以将同样的知识应用到Vanilla JS解决方案中来获得滚动条的位置。这将使两个div之间的滚动更加平滑。

/** Scroll sync between editor and preview **/
// Locks so that only one pane is in control of scroll sync
var eScroll = false;
var pScroll = false;
// Set the listener to scroll
this.edit.on('scroll', function() {
    if(eScroll) { // Lock the editor pane
        eScroll = false;
        return;
    }
    pScroll = true; // Enable the preview scroll

    // Set elements to variables
    let current = self.edit.get(0);
    let other = self.preview.get(0);

    // Calculate the position of scroll position based on percentage
    let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);

    // Set the scroll position on the other pane
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
});
this.preview.on('scroll', function() {
    if(pScroll) { // Lock the preview pane
        pScroll = false;
        return;
    }
    eScroll = true; // Enable the editor scroll

    // Set elements to variables
    let current = self.preview.get(0);
    let other = self.edit.get(0);

    // Calculate the position of scroll position based on percentage
    let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);

    // Set the scroll position on the other pane
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);

});
im9ewurl

im9ewurl3#

我添加了两个DOM操作函数

function scrollSynchronizeY(element1,element2){
  document.querySelector(element1).addEventListener('scroll',function(e){
    document.querySelector(element2).scrollTop = e.target.scrollTop;
  })
  document.querySelector(element2).addEventListener('scroll',function(e){
    document.querySelector(element1).scrollTop = e.target.scrollTop;
  })
}
function scrollSynchronizeX(element1,element2){
  document.querySelector(element1).addEventListener('scroll',function(e){
    console.log('scrolled left ',e.target.scrollLeft);
    document.querySelector(element2).scrollLeft = e.target.scrollLeft;
  })
  document.querySelector(element2).addEventListener('scroll',function(e){
    document.querySelector(element1).scrollLeft = e.target.scrollLeft;
  })
}
flvlnr44

flvlnr444#

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

这里我们使用.scrollTop(),从带有滚动条的元素中获取scrollTop值,并为其他元素设置scrollTop以同步它们的滚动位置:http://api.jquery.com/scrollTop
这里假设底部元素的ID为bottom,顶部元素的ID为top
您可以使用CSS隐藏top元素的滚动条:

#top {
    overflow : hidden;
}

下面是一个演示:http://jsfiddle.net/sgcer/1884/
我想我从来没有真正的理由这样做,但它看起来很酷的行动。

ubof19bj

ubof19bj5#

我知道这是一个老帖子,但也许这会对某些人有帮助。如果你需要同步双向滚动,仅仅处理两个容器的滚动事件并设置滚动值是不够的,因为滚动事件会进入循环,滚动不平滑(尝试通过鼠标滚轮垂直滚动,Hightom给出了一个例子)。
以下是如何检查是否已同步滚动的示例:

var isSyncingLeftScroll = false;
var isSyncingRightScroll = false;
var leftDiv = document.getElementById('left');
var rightDiv = document.getElementById('right');

leftDiv.onscroll = function() {
  if (!isSyncingLeftScroll) {
    isSyncingRightScroll = true;
    rightDiv.scrollTop = this.scrollTop;
  }
  isSyncingLeftScroll = false;
}

rightDiv.onscroll = function() {
  if (!isSyncingRightScroll) {
    isSyncingLeftScroll = true;
    leftDiv.scrollTop = this.scrollTop;
  }
  isSyncingRightScroll = false;
}
.container {
  width: 200px;
  height: 500px;
  overflow-y: auto;
}

.leftContainer {
  float: left;
}

.rightContainer {
  float: right;
}
<div id="left" class="container leftContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>
<div id="right" class="container rightContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>

这是fiddle

7vhp5slm

7vhp5slm6#

好了,我评估了这里提供的所有选项,它们都有这样或那样的限制:

  • accepted answer在使用鼠标滚轮时存在已知问题。
  • next highest upvote没有滚轮问题,但只适用于两个已知元素。如果你需要更多的元素,它是不可扩展的。
  • 唯一显示出promise的解决方案是Lacho's,但是代码中有一些已知的元素引用没有包含在代码片段中。从好的方面来说,它具有性能所需的结构,并且它是在TypeScript中。

我利用它创建了一个可重用的版本,它可以处理无限数量的元素,并且不需要JQuery。

function scrollSync(selector) {
  let active = null;
  document.querySelectorAll(selector).forEach(function(element) {
    element.addEventListener("mouseenter", function(e) {
      active = e.target;
    });

    element.addEventListener("scroll", function(e) {
      if (e.target !== active) return;

      document.querySelectorAll(selector).forEach(function(target) {
        if (active === target) return;

        target.scrollTop = active.scrollTop;
        target.scrollLeft = active.scrollLeft;
      });
    });
  });
}

//RWM: Call the function on the elements you need synced.
scrollSync(".scrollSync");

你可以在这里查看JSFiddle:http://jsfiddle.net/gLa2ndur/3。您可以看到它同时使用了水平和垂直滚动示例。
唯一已知的限制是,它可能无法在不同大小的div上工作。我相信如果你的用例认为有必要(我的用例没有),有人可以将Andrew's work合并到其中。
希望这对某人有帮助!

velaa5lx

velaa5lx7#

我一直在寻找一个双向的解决方案,感谢你们所有人,你们的贡献帮助我做到了这一点:

$('#cells').on('scroll', function () {
$('#hours').scrollTop($(this).scrollTop());
$('#days').scrollLeft($(this).scrollLeft());});

参见JSFiddle:https://jsfiddle.net/sgcer/1274/
希望有一天能帮助到别人:-)

tjjdgumg

tjjdgumg8#

另一个解决方案可以防止这种循环问题,并实现平滑的滚动。这可以确保只有被聚焦的元素获得滚动事件。

let activePre: HTMLPreElement = null;
document.querySelectorAll(".scrollable-pre").forEach(function(pre: HTMLPreElement) {
    pre.addEventListener("mouseenter", function(e: MouseEvent) {
        let pre = e.target as HTMLPreElement;
        activePre = pre;
    });

    pre.addEventListener("scroll", function(e: MouseEvent) {
        let pre = e.target as HTMLPreElement;

        if (activePre !== pre) {
            return;
        }

        if (pre !== versionBasePre) {
            versionBasePre.scrollTop = pre.scrollTop;
            versionBasePre.scrollLeft = pre.scrollLeft;
        }

        if (pre !== versionCurrentPre) {
            versionCurrentPre.scrollTop = pre.scrollTop;
            versionCurrentPre.scrollLeft = pre.scrollLeft;
        }

    });
});

相关问题