gpt4 book ai didi

jquery - 我如何使用 jQuery 添加 margin-bottom

转载 作者:行者123 更新时间:2023-12-03 23:05:23 26 4
gpt4 key购买 nike

这是我正在使用的代码,它在滚动时将 div 固定到页面顶部,但我想给 div 一个 margin > 将其固定到顶部后。

var fixmeTop = $('.fixme').offset().top;
$(window).scroll(function() {
var currentScroll = $(window).scrollTop();
if (currentScroll >= fixmeTop) {
$('.fixme').css({
position: 'fixed',
top: '0',
left: '0'
});
} else {
$('.fixme').css({
position: 'static'
});
}
});

我见过这样的例子,使用 jQuery 添加边距,但我无法将其应用于我的代码:

$('.fixme').css('margin-bottom',90);

您会看到,当 div 固定到页面顶部时,两个元素之间的空间会闭合。我想在之后的 div 中添加 margin,以便它一旦粘住就具有相同的距离。

FIDDLE

最佳答案

You'll see that when the div gets fixed to the top of the page the space between the two elements closes up. I want to add margin to the div after so that it has the same distance as soon as it sticks.

你不能这么做。这是因为,一旦某个元素被固定,它就会从流中删除,并与其余内容完全位于不同的层中。将边距放在 fixed 元素上将不起作用,因为它位于不同的层中。内容从这个 div 后面滚动过去,并且您无法控制间距。无论如何,内容都会被这个 div 覆盖。检查这个 fiddle 看看我的意思(添加阴影以帮助您可视化图层):

演示 fiddle 1:http://jsfiddle.net/abhitalks/3Lv6fL7r

如果您只是想避免该 div 突然跳转,只需向该 div 添加 margin-top 即可。或者(更好的方法),将这些样式保留在 CSS 中并应用/删除这些类。

演示 fiddle 2:http://jsfiddle.net/abhitalks/zu75wpqm/5

注意:当您通过 Javascript 将其用作属性时,您需要 marginTop 而不是 margin-top

关于jquery - 我如何使用 jQuery 添加 margin-bottom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33495971/

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