gpt4 book ai didi

javascript - 使用 jQuery 粘性 DIV

转载 作者:行者123 更新时间:2023-11-28 01:41:10 25 4
gpt4 key购买 nike

我使用 jQuery 制作了一个 DIV。但是,它有效,我正在尝试使其向下或向上滚动,如本页所示:http://www.southbayfuso.com/custom-bodies.php 。请注意“快速报价”DIV 如何暂停一两秒,然后平滑地向上或向下滚动。我可以在代码中添加什么,以便我的粘性 DIV 能够像上面示例中的那样滚动?感谢您的帮助。

<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>

最佳答案

看看jQuery throttle/debounce .

$(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')
}));

要更新现有代码:

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.
}
});
});

关于javascript - 使用 jQuery 粘性 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com