首页 > 解决方案 > 使用 jQuery 在滚动时更改背景附件属性

问题描述

我有一个 div,它有一个背景图像,背景附件是固定的。当带有背景图像的 div 中途使用 jQuery 时,我从固定更改为滚动。我似乎已经让它工作了但是当我向下滚动时,当属性改变时似乎有跳跃。我怎样才能避免这种跳跃?

$(window).scroll(function() {
  var halfHeight = $(window).height() / 2
  if ($(this).scrollTop() >= $('.service-logo').offset().top + halfHeight) {
    $('.service-logo').addClass('bg-scroll');
  } else {
    $('.service-logo').removeClass('bg-scroll');
  }
});
.content {
  background: red;
  height: 1000px;
}

.content2 {
  background: black;
  height: 1000px;
}

.service-logo {
  background-image: url(https://www.w3schools.com/css/img_5terre.jpg);
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 200px;
  background-position: center;
}

.bg-scroll {
  background-attachment: scroll !important;
}

.content3 {
  background: green;
  height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div class="content">

</div>

<div class="content2 service-logo">

</div>


<div class="content3">

</div>

标签: javascriptjqueryhtmlcss

解决方案


看起来像这样

background-position: center;

根据图像高度和background-size.

如果您手动将位置设置为 content2 的中间,那么它可以顺利运行:

      background-position: center 200px;

$(window).scroll(function() {
  //var halfHeight = $(window).height() / 2
  if ($(this).scrollTop() >= $('.service-logo').offset().top) {
    $('.service-logo').addClass('bg-scroll');
  } else {
    $('.service-logo').removeClass('bg-scroll');
  }
});
.content {
  background: red;
  height: 1000px;
}

.content2 {
  background: black;
  height: 1000px;
}

.service-logo {
  background-image: url(https://www.w3schools.com/css/img_5terre.jpg);
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 200px;
  background-position: center 400px;
}

.bg-scroll {
  background-attachment: scroll !important;
}

.content3 {
  background: green;
  height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div class="content"></div>
<div class="content2 service-logo"></div>
<div class="content3"></div>

(片段最好运行整页或通过“编辑此片段” - 在小片段运行窗口中实际上不起作用)


推荐阅读