How to slide two elements apart as page scrolls down?
Can someone help suggest a good way to achieve the following please?
I want two overlapping images (doesn't really matter that they're images) to slide apart as the page scrolls down and they come into view, and slide back together as they go out of view. Think of how a zip works.
From another script I think it could be achieved by adapting the following but I still can't get my head around it:
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');
}
});
But this would only trigger the event once as the开发者_StackOverflow中文版 .container
comes into view.
How can I make it so that the more the container scrolls into view, the more the distance between the images increases?
You are just setting/removing a class, so you aren't going to get animated movement. You should try setting position or margins relative to the y
variable.
simple example to give you an idea:
.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);
});
See jsFiddle here
精彩评论