我想实现这样一种效果
页面是可以滚动的,黄色的部分是固定定位。页面向上滚动的时候,当粉丝区域接触到黄色区域时,黄色区域也将随着滚动直至滚出窗口,粉色区域变成固定定位到顶部。当页面下向下滚动时,粉色区域有由固定定位变成随着页面滚动,黄色区域也滚动出来再次固定定位到顶部。
我把代码补上来,麻烦大家帮我看看应该怎么实现,谢谢。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>哈哈哈哈哈</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
/* width: 400px; */
margin: 0 auto;
background-color: red;
height: 300px;
overflow: scroll;
}
.p {
width: 300px;
height: 700px;
background-color: green;
position: relative;
}
.p1 {
width: 300px;
height: 700px;
background-color: blue;
}
.topbar {
position: fixed;
width: 300px;
background-color: yellow;
top: 0px;
left: 0;
}
h4 {
width: 100%;
background-color: pink;
}
</style>
</head>
<body>
<div id="scroll">
<section class="p">
<p class="topbar">kkkkk</p>
</section>
<section class="p1">
<h4>lllll</h4>
</section>
</div>
</body>
<script>
var scrollbar = document.querySelector('h4');
var topbar = document.querySelector('.topbar');
document.querySelector('#scroll').addEventListener('scroll', function(){
var top = scrollbar.getBoundingClientRect().top;
if(top <= topbar.offsetHeight){
console.log(111);
}
})
</script>
</html>
你可以看看我这两篇博客,我基本上每周整理一遍这两篇没丢目录里面
https://www.cnblogs.com/pythonywy/p/11617664.html,
https://www.cnblogs.com/pythonywy/p/11627992.html
其实你博客头上的那个目录就蛮符合他的要求的,另外你生活照太丑了
@轻红: 我吴彦祖居然丑
getBoundingClientRect判断高度top,可以得到结果
var p_pink = document.querySelector('h4');
var p_yello = document.querySelector('.topbar');
var p_yello_rect = p_yello.getBoundingClientRect();
var p_pink_rect = p_pink.getBoundingClientRect();
var p_yello_rect_pre = p_yello.getBoundingClientRect();
var p_pink_rect_pre = p_pink.getBoundingClientRect();
document.querySelector('#scroll').addEventListener('scroll', function () {
var p_link_rect_cur = p_pink.getBoundingClientRect();
var p_yello_rect_cur = p_yello.getBoundingClientRect();
//scroll to yello
if (p_pink_rect_pre.top != 0 && p_link_rect_cur.top <= 0) {
p_yello.style.position = 'static'
p_pink.style.position = 'fixed';
// p_pink.style.width = '300px';
p_pink.style.top = 0;
p_pink.style.left = 0;
}
//scroll to pink
if (p_yello_rect_pre.top != 0 && p_yello_rect_cur.top * -1 <= p_pink_rect.top) {
p_pink.style.position = 'static'
p_yello.style.position = 'fixed';
p_yello.style.top = 0;
p_yello.style.left = 0;
}
p_yello_rect_pre = p_yello.getBoundingClientRect();
p_pink_rect_pre = p_pink.getBoundingClientRect();
});
换个思路粉色盖住黄色区域,那么你这个问题就变成了粉色滚动到页面顶部fixed固定住就行呗