javascript - 将空间保持在固定背景上方,您向上滚动

标签 javascript jquery html css

我有一个背景,当你向下滚动浏览 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/

相关文章:

javascript - 如何按日期对数组进行排序但缺少第一个数组项

javascript - 如何检测用户第一次登录和第一次加载特定页面?

javascript - 我怎样才能让事件多次触发。

html - CSS fit-content 不适用于 Microsoft-Edge

javascript - 按键时使用 Ember 操作第一个字符为空

javascript - Jssor Slider 移动兼容性问题

javascript - jQuery 的 .click() 方法适用于 Bootstrap 星级评定吗

jquery - 每次单击按钮时切换一个变量值

jquery - 使用 CSS 或 jQuery 更改文本框光标颜色

java - 我的语言翻译在谷歌浏览器和 IE 中不起作用