This might be a simple question but please help! I have implemented a sticky div
using the code below but I need to know how to change the position at which the div
gets 'stuck'?
What I want is for my div
to only get stuck when 50% of it has been scrolled passed the top. At the moment it gets stuck when it reaches the top but I would like 50% of it to keep scrolling to the halfway (roughly) before it gets stuck.
$(document).ready(function() {
var s = $("#picture1");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
//$("#header_left").html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
if (windowpos >= pos.top) {
s.addClass("stick");
} else {
s.removeClass("stick");
}
if (windowpos >= pos.top) { s.addClass("stick"); $("body").css("margin-top", s.height()); } else { s.removeClass("stick"); $("body").css("margin-top", 0); }
});
});
and CSS
.stick {
position:fixed;
top:0px;
/*_top: expression( ie6 = (document.documentElement.scrollTop + "px") );*/
z-index: 1000;
}
change windowpos >= pos.top
to windowpos >= (s.height()/2) + pos.top
EDIT
The div get's .stick
style only when your div goes up by 50%. But when you apply fixed
position to some div, it gets out from the normal layout and you loses the ability to get any margin on themselves. So, you have to apply margin or padding to the body in this case, which you have already done as well.
Anyways, I have just tweak your code a little to show how you can get what you want.
$(document).ready(function() {
var s = $("#picture1"),
pos = s.position(),
sHeight = s.height();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= (sHeight/2) + pos.top) {
s.addClass("stick");
$('body').css('paddingTop', sHeight + 60);
} else {
s.removeClass("stick");
$('body').css('paddingTop', '0');
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.