gpt4 book ai didi

javascript - 使用 jQuery 更改滚动时的背景附件属性

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:26 24 4
gpt4 key购买 nike

我有一个 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>

最佳答案

尝试使用此脚本,您将通过此代码在任何屏幕上获得完美定位。

$(window).scroll(function() {
var sectionHeight = $('.service-logo').height();
var windowHeight = $(window).height();
if ($(window).scrollTop() >= $('.service-logo').offset().top + ((sectionHeight - windowHeight) / 2)) {
$('.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://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="content">
</div>
<div class="content2 service-logo">
</div>
<div class="content3">
</div>

谢谢你...

关于javascript - 使用 jQuery 更改滚动时的背景附件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com