javascript - 背景图像在第一次滚动时跳转

标签 javascript jquery html css parallax

我正在尝试为我的背景图片制作一个简单的视差效果,一切似乎都正常,但背景图片在第一次滚动时跳转,然后就可以了!我似乎无法弄清楚为什么它继续跳跃,实时预览:http://loai.directory/gallery

HTML:

<div class="topSection parallax">
         <div class="content">
         </div>
      </div>

CSS:

#page {
   background-color: #3F8AE4;
   padding-top: 80px;
   text-align: left;
}

   /*Wrappers*/
   .wrapper {
      background-color: #ffffff;
   }

   .wrapper.A {
      background-color: #EDEDED;
      border-top: 1px solid rgba(0,0,0,0.1);
      border-bottom: 1px solid rgba(0,0,0,0.1);
   }

      /*Content Container*/
      .content {
         width: 1024px;
         padding: 50px 20px;
         margin: auto;
         overflow: hidden;
         position: relative;
      }

   /*Top Section*/
   .topSection {
      color: #fff;
      background-color: #3F8AE4;
      border-bottom: 1px solid rgba(0,0,0,0.1);
      padding: 10px 0;
   }

.parallax {
   background: url(../images/backgruond.jpg) no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   padding: 150px 0;
}

JS:

// Y axis scroll speed
var velocity = 0.5;

function update(){ 
    var pos = $(window).scrollTop(); 
    $('.topSection').each(function() { 
        var $element = $(this);
        // subtract some from the height b/c of the padding
        var height = $element.height()-0;
        $(this).css('background-position', '50%' + Math.round((height - pos) * velocity) + 'px'); 
    }); 
};

$(window).bind('scroll', update);

最佳答案

您的 background-position 通过默认 CSS 设置为 center center,但是一旦您开始滚动,它就会设置为 50% 50px ...所以跳跃来自从居中到计算的垂直位置。

您可以通过两种方式解决这个问题,要么将您的初始 css 设置为:

background: url(../images/backgruond.jpg) no-repeat 50% 50px fixed;

因为您知道这是您开始滚动时设置的位置,

或者,除了滚动之外,只需在页面加载时调用您的 update() 函数,从而允许立即计算位置。

例如:

$(window).bind('scroll', update);
update();

关于javascript - 背景图像在第一次滚动时跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23225166/

相关文章:

css - 使用 iframe 时,如何始终保持最大高度 Angular 4

javascript - jQuery 颜色盒上没有下一个/上一个按钮

javascript - 点击事件后显示图表

javascript - aurelia、es6 和类名大小写

javascript - 如何使用 taggingjs 避免空白初始化

javascript - 如何绑定(bind)国家/地区更改国际电话输入

jquery - 多个 jQuery niceScroll 插件

Javascript 游戏循环

javascript - 在外部 .js 文件中使用 .vue 组件时如何使用相同的变量?

javascript - 如何通过对象的唯一属性值从数组中获取对象?