如何在页面向下滚动时将两个元素滑开

How to slide two elements apart as page scrolls down?

本文关键字:两个 元素 滚动      更新时间:2023-09-26

有人能帮忙建议一个实现以下目标的好方法吗?

我希望两个重叠的图像(它们是图像并不重要)在页面向下滚动并进入视图时滑动分开,在视图外滑回一起。想想拉链是如何工作的。

从另一个剧本来看,我认为可以通过改编以下内容来实现,但我仍然无法理解:

var top = $('.container').offset().top - parseFloat($('.container').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
  $('.imageA').addClass('moveLeft');
  $('.imageB').addClass('moveRight');
  }
else {
  $('.imageA').removeClass('moveLeft');
  $('.imageB').removeClass('moveRight');
  }
});

但这只会在.container进入视图时触发事件一次。

如何使容器滚动到视图中的次数越多,图像之间的距离就越大?

您只是在设置/删除一个类,所以您不会得到动画移动。您应该尝试设置相对于y变量的位置或边距。

给你一个想法的简单例子:

.left {
    width: 100px;
    height: 100px;
    background-color: #f99;
    position: absolute;
    right: 50%;
    bottom: 0;
}
.right {
    width: 100px;
    height: 100px;
    background-color: #9f9;
    position: absolute;
    left: 50%;
    bottom: 0;
}
$(window).scroll(function (event) {
    var y = $(this).scrollTop();
    $('.left').css('marginRight', y/5);
    $('.right').css('marginLeft', y/5);
});

请参阅jsFiddle此处的