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

How would I add margin-bottom using jQuery

这是我正在使用的代码,它在滚动时将 div 固定到页面顶部,但我想在 div 固定到顶.

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 固定在页面顶部时,两个元素之间的 space 闭合。我想将 margin 添加到 div 之后,以便它在粘贴后具有相同的距离。

FIDDLE

只需将它添加到您的 .css 函数中(如果)div 已修复:

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

可以在if语句中添加margin bottom:

    $('.fixme').css({
        position: 'fixed',
        top: '0',
        left: '0',
        marginBottom: '5%' // you can write with quotes "margin-bottom" too
    });

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,它就会从流中移除,并且与您的其余内容完全位于不同的层中。在 fixed 元素上放置边距将不起作用,因为它位于不同的层中。内容从 div 后面滚动过去,您无法控制间距。无论如何,内容将被此 div 掩盖。检查此 fiddle 以了解我的意思(添加阴影以帮助您可视化图层):

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

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

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

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