[英]Sticky DIV with jQuery
I made a DIV that sticks using jQuery. 我制作了一个使用jQuery的DIV。 It works, however, I'm trying to make it so that it scrolls down or up, as seen on this page: http://www.southbayfuso.com/custom-bodies.php .
它可以工作,但是,我正在尝试使其向下或向上滚动,如本页所示: http : //www.southbayfuso.com/custom-bodies.php 。 Notice how the "Quick Quote" DIV pauses for a second or two before smoothly scrolling up or down.
请注意“快速报价” DIV如何暂停一两秒钟,然后才能平滑地向上或向下滚动。 What can I add to my code so that my sticky DIV scrolls just like the one on the example above?
我可以在代码中添加些什么,以便粘性DIV像上面示例中的那样滚动? Thanks for any help.
谢谢你的帮助。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
var s = jQuery("#sticker");
var pos = s.position();
var stickermax = jQuery(document).outerHeight() - jQuery("#footer").outerHeight() - s.outerHeight() - 40; // 40 value is the total of the top and bottom margin.
jQuery(window).scroll(function() {
var windowpos = jQuery(window).scrollTop();
if (windowpos >= pos.top && windowpos < stickermax) {
s.attr("style", ""); // Turn off absolute positioning.
s.addClass("stick"); // Stick it.
} else if (windowpos >= stickermax) {
s.removeClass(); // Unstick.
s.css({position: "absolute", top: stickermax + "px"}); // Set sticker right above the footer.
} else {
s.removeClass(); // Top of page.
}
});
});
</script>
Take a look at jQuery throttle/debounce . 看一下jQuery油门/反跳 。
$(window).scroll($.throttle( 250, function(){
console.log('only once every 250 ms')
}));
$(window).scroll($.throttle( 250, function(){
console.log('only only called after the scroll event hs stopped firing for 250 ms')
}));
To update your existing code: 更新现有代码:
jQuery(document).ready(function() {
var s = jQuery("#sticker");
var pos = s.position();
var stickermax = jQuery(document).outerHeight() - jQuery("#footer").outerHeight() - s.outerHeight() - 40; // 40 value is the total of the top and bottom margin.
jQuery(window).scroll($.throttle( 250, function(){
var windowpos = jQuery(window).scrollTop();
if (windowpos >= pos.top && windowpos < stickermax) {
s.attr("style", ""); // Turn off absolute positioning.
s.addClass("stick"); // Stick it.
} else if (windowpos >= stickermax) {
s.removeClass(); // Unstick.
s.css({position: "absolute", top: stickermax + "px"}); // Set sticker right above the footer.
} else {
s.removeClass(); // Top of page.
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.