在滚动时如何在特定位置停止元素?
这是我使用的源代码。
body {
height: 100vh;
margin: 0;
padding: 0;
}
.s1, .s2, .s3 {
height: 100vh;
}
.s1 {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid green;
}
.s2 {
display: flex;
justify-content: center;
align-items: center;
background-color: aqua;
border: 1px solid aqua;
}
.s3 {
background-color: beige;
}
.s1 .p1 {
position: fixed;
}
<html>
<body>
<div class="s1">
<p class="p1">TEST</p>
</div>
<div class="s2">
<p class="p2">STOP HERE</p>
</div>
<div class="s3">
</div>
</body>
</html>
简单的代码。我为.s1的position: fixed
标签定义了<p>
。
因此<p>
总是在向下或向上滚动时漂浮在屏幕中央。
向下滚动时,如果.s1的<p>
标记遇到.s2的<p>
标记,则必须停止。
此外,如果向上滚动,.s1的<p>
标签也必须向上移动。
我想用纯html / css / js实现此问题。
但是有可能使用库。 (也许它必须使用视差滚动或其他方式。我不完全知道)
这里有什么解决办法吗?
谢谢。
答案 0 :(得分:1)
我添加了一个控制台日志,以便在滚动时可以看到.s1 p
触摸.s2 p
的情况。
window.onload = function() {
let s1P = document.querySelector('.s1 p');
let s2P = document.querySelector('.s2 p');
let scroll = () => {
let coordS1P = s1P.getBoundingClientRect();
let coordS2P = s2P.getBoundingClientRect();
// touched while scrolling down condition
if(coordS1P.bottom > coordS2P.top && coordS1P.top < coordS2P.bottom) console.log('touched!');
// touched while scrolling up condition
else if(coordS1P.bottom > coordS2P.top && coordS1P.top < coordS2P.bottom) console.log('touched!');
};
window.addEventListener('scroll', scroll, true);
}
body {
height: 100vh;
margin: 0;
padding: 0;
}
.s1, .s2, .s3 {
height: 100vh;
}
.s1 {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid green;
}
.s2 {
display: flex;
justify-content: center;
align-items: center;
background-color: aqua;
border: 1px solid aqua;
}
.s3 {
background-color: beige;
}
.s1 .p1 {
position: fixed;
}
<html>
<body>
<div class="s1">
<p class="p1">TEST</p>
</div>
<div class="s2">
<p class="p2">STOP HERE</p>
</div>
<div class="s3">
</div>
</body>
</html>
答案 1 :(得分:0)
您的意思是这样吗?
let stop = $('#stop').offset().top - $(window).innerHeight() / 2;
$(window).on('scroll', function(){
let depth = $(window).scrollTop();
if ( stop <= (depth) ) {
$('.p1').css('position', 'absolute');
$('#stop').text('TEST');
} else {
$('.p1').css('position', 'fixed');
$('#stop').text('');
}
});
body {
height: 100vh;
margin: 0;
padding: 0;
}
.s1, .s2, .s3 {
height: 100vh;
}
.s1 {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid green;
}
.s2 {
display: flex;
justify-content: center;
align-items: center;
background-color: aqua;
border: 1px solid aqua;
}
.s3 {
background-color: beige;
}
.s1 .p1 {
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="s1">
<p class="p1">TEST</p>
</div>
<div class="s2">
<p class="p2" id="stop"></p>
</div>
<div class="s3"></div>