gpt4 book ai didi

javascript - 修复定位元素在滚动时停在某个点

转载 作者:行者123 更新时间:2023-11-30 08:38:30 24 4
gpt4 key购买 nike

box2 是一个固定定位的元素,我需要它在滚动时停在 box1 的顶部和底部。任何帮助,将不胜感激。

   $(window).scroll(function() {
var h1 = $('.box1').height();
var h2 = $('.box2').height();
var h3 = $('.footer').outerHeight(true);
$('.box2').css('bottom', h3);
});

example

最佳答案

如果我对问题的理解正确,您希望 box2 在视口(viewport)中显示为静态,除非它永远不会超过或低于 box1 的范围。

使用这段代码:

$(window).scroll(function() {
var scrollTop= $(window).scrollTop(),
b1= $('.box1'),
b2= $('.box2'),
min= b1.position().top,
max= (b1.position().top + b1.outerHeight()) - b2.outerHeight();

b2.css({
top: Math.min(Math.max(scrollTop,min),max) - scrollTop
});
});

Working Fiddle

关于javascript - 修复定位元素在滚动时停在某个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29128938/

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