magnetic div: fixed div inside absolute positioned div
I have the following page:
[LINK]
The page is designed to be scrolled horizontally, so that a series of divs (black bordered ones) appear in a row.
Now, I the smaller divs inside (red ones) to behave so that they never go outside the parent div but at the same time, while scrolling the page, I want them to move inside the parent div like if they were fixed-positioned.
I'll explain myself with a diagram. I want my divs to behave like this:
[LINK]
Anyone can help? Thanks for your time!
UPDATE
created some minimal/experimental jQuery plugin: https://gist.github.com/3177804
you should be able to use it like this: http://jsfiddle.net/7q3Zu/2/
download and include the plugin https://raw.github.com/gist/3177804/556074672de8f200327d83f0146d98533c437ac3/jquery.magnetic.js then call it like this:
$(function() {
$('.container').magnetic({ //call it on some scrollable container
selector: '.object', //what to fix
left: 180, //when to fix (px)
right: 500 //when to unfix (px)
});
});
atm this is just an experiment with no warranty of working in any browser
(so feel free to grab the gist and improve it :)
As mentioned in the comments, you could do this with Javascript.
Here's am example using jQuery:
http://jsfiddle.net/7q3Zu/
HTML
<div class="container">
<div class="object"></div>
</div>
JS
$(function() {
var obj = $('.object');
$(document).on('scroll', function() {
var offset = $(this).scrollLeft()
//fix the position a some point
if (offset >= 200) {
obj.css('position', 'fixed').css('left', '20px');
}
//..and unfix it later
if (offset >= 500) {
obj.css('position', 'absolute').css('left', '500px');
}
});
});
CSS
.container{
width: 4000px;
padding: 20px;
margin: 20px;
border: 1px solid #ccc;
height: 400px;
position: relative;
}
.object{
position: absolute;
height: 400px;
width :100px;
background: red;
left: 200px;
}
链接地址: http://www.djcxy.com/p/11050.html