How to have 2+ boxes slide down
I have been reading tutorials from several different places like http://css-tricks.com/scrollfollow-sidebar/ or ht开发者_开发问答tp://jqueryfordesigners.com/fixed-floating-elements/ and have been playing around with them but cant seem to figure out how I would be able to add more then just that one sliding box on the page. Any thoughts?
My assumption (from the first example link) is that instead of just having #sidebar
stay in view, you want to have another element scroll with the window as well (i.e. logged in user's details).
The easiest way would be to add this information to your existing scrolling element:
<ul id="sidebar">
<li id="user-details">Name: John Doe<br/>Email: john.doe@gmail.com</li>
<!-- remaining links here -->
</ul>
However, if you want to scroll two elements with the window:
<ul id="sidebar">
<!-- sidebar links -->
</ul>
<ul id="user-details">
<!-- user details -->
</ul>
It would just be a matter of animating both of their margin-top's inside the $(window).scroll()
event handler:
Edit
The following code scrolls #sidebar
until it reaches 2000px of scroll at which point it stops and scrolls #user-details
until it reaches 4000px of scroll:
// constants for the scrolling
var offsetSidebar = $("#sidebar").offset();
var offsetUserDetails = $("#user-details").offset();
// on scroll of window
$(window).scroll(function() {
scrollElement($("#sidebar"), offsetSidebar, 2000);
scrollElement($("#user-details"), offsetUserDetails, 4000);
});
// handle the scrolling
function scrollElement(elem, offset, boundary){
var currOffset = elem.offset();
if(currOffset.top < boundary && $(window).scrollTop() < boundary){
if ($(window).scrollTop() > offset.top) {
elem.stop().animate({marginTop: $(window).scrollTop() - offset.top});
} else {
elem.stop().animate({marginTop: 0});
}
}
}
You can see it in action here.
精彩评论