本文主要是介绍粘性定位应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
现象:当页面滑动到某个位置时,图片吸顶。
思路:创建一个father背景。包含内容和需要吸顶的背景图
当滚轮运动距离大于800px时,将吸顶图的position设置为sticky,距离顶部改为0px。
html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
</head>
<style>
.back{
background-image: url(img/b3.jpg);
/* background-repeat: no-repeat; */
top: 800px;
height: 1080px;
width: 1000px;
position: absolute;
}
.content{
position: absolute;
top: 9px;
}
.p{
font-size: 110px;
color: cornflowerblue;
border: 1px solid rebeccapurple;
}
.father{
width: auto;
height: 8000px;
background-color: gray;
}
</style>
<script src="js/jquery-3.7.0.min.js"></script>
<script src="js/back.js">
</script>
<body>
<div class="father">
<div class="back">背景图</div>
<div class="content">
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
<div class='p'>大家好我是渣渣灰</div>
</div>
</div>
</body>
<script>
ScrollEvent()
</script>
</html>
JS代码:
function ScrollEvent(){
addEventListener("scroll", (event) => {
const scrollX = window.scrollX;
const scrollY = window.scrollY;
if ( 0<=scrollY && scrollY<=800){
//$('.back').css('background-attachment', 'scroll')
$('.back').css('position', 'absolute')
$('.back').css('top', '800px')
}else if(800<scrollY){
//$('.back').css('background-attachment', 'fixed')
$('.back').css('position', 'sticky')
$('.back').css('top', '0px')
}
});
}
这篇关于粘性定位应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!