javascript - 使用 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>
解决方案
看起来像这样
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>
(片段最好运行整页或通过“编辑此片段” - 在小片段运行窗口中实际上不起作用)
推荐阅读
- firebase - Vuejs 和 Firebase 存储问题。未捕获的类型错误:存储不是函数
- php - 将可点击的电话号码添加到 php 邮件
- asp.net-core - 使用 VS2019 和 ASP.NET 核心通过 SSH 附加到进程不起作用
- r - 在 R 中拆分()之后保持数据的原始顺序
- javascript - 为通过 window.open() 打开的外部页面应用 CSS
- html - 粘性侧边栏在 Firefox 中没有正确的顶部空间
- c# - 鉴于一台服务器上的 ASP.Net MVC 站点但另一台服务器上的 ASP.Net MVC 站点,HttpContext.Current.User.Identity 为空/空
- python - 芹菜任务的 finally 子句不执行,我该如何清理?
- python - Pandas Dataframe 到嵌套数据结构
- node.js - 带有Angular的Node.js - 我发送请求时出现CORS错误