我有一个背景,当你向下滚动浏览 JS 时,我将一个固定的类附加到它上面,这导致它成为一个固定的附件,但是背景图像在它到达顶部之前不会开始消失在内容后面,我会就像在内容滚动时背景图像上方有一点空间,比如 20 - 40 像素的空间。
你可以在我的例子中看到这个 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
id'd div。我更新了你的 fiddle :http://jsfiddle.net/4VkBL/2/
关于javascript - 将空间保持在固定背景上方,您向上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23448830/