在你向上滚动的固定背景上方保持空间

Keep Space above a fixed background you scroll up

本文关键字:背景 方保持 空间 滚动      更新时间:2023-09-26

我有一个背景,当你通过JS向下滚动时,我将一个固定的类附加到它,这导致它成为一个固定的附件,但背景图像不会开始消失在内容后面,直到它达到顶部,我希望有一个小的空间说20 - 40px的空间在背景图像之上,而内容在它上面滚动。

您可以在http://jsfiddle.net/4VkBL/

的示例中看到这一点

当页面开始时,背景上方有空间,但是当它到达滚动点时,背景触及顶部,我仍然希望在BG和页面顶部之间有空间。

#about-banner {
background-image: url('http://hearthable.com/img/hearthable/about/test.jpg');
width: 700px;
height: 325px;
background-repeat: no-repeat;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.about-fixed {
    background-attachment: fixed;
 }
 $(document).ready(function () {
 var top = $('#about-banner').offset().top - 20 - parseFloat($('#about-  banner').css('marginTop').replace(/auto/, 0));
 $(window).scroll(function (event) {
     // what the y position of the scroll is
     var y = $(this).scrollTop();
     // whether that's below the form
     if (y >= top) {
         // if so, ad the fixed class
         $('#about-banner').addClass('about-fixed');
     } else {
         // otherwise remove it
         $('#about-banner').removeClass('about-fixed');
     }
 });
});

添加与您需要的空白相等的background-position,您应该可以使用:

#about-banner {
    background-position:0 40px;
    /* ... */
}

同样,为了让它正常工作,你实际上不需要任何js。只需将background-attachment: fixed;添加到横幅中;在这种情况下,您实际上也不需要您的top iddiv。我更新了你的小提琴:http://jsfiddle.net/4VkBL/2/

你可以使用CSS的background-position作为about-fixed类。

.about-fixed {
    background-attachment: fixed;
    background-position: 8px 40px;
}

JSFiddle: http://jsfiddle.net/f95Qy/1/