我有一个横幅(.banner
)和浮动元素(.float
)的页面。
当用户在视图中滚动横幅时,我希望.float
相对于横幅(垂直居中)出现,但是当用户滚过横幅时,它会粘在屏幕上。
实际上,浮点数的位置总是fixed
,我使用Javascript来改变变换值,将其定位在我想要滚动的位置。
它几乎按照我的意愿工作,但我希望元素在位置之间“滑动”,我不能让这种行为按照我的意愿工作。没有CSS过渡,它会跳跃。通过CSS过渡,它会滑动,但是当我向后滚动时,它会在横幅的垂直中心上方滑动太远;一旦你滚动回横幅,我希望它能够“贴上”横幅。
任何帮助赞赏。 JSFiddle:http://jsfiddle.net/L452xf7h/12/
HTML:
<div class="container">
<div class="banner"></div>
<div class="float">Floating Element</div>
</div>
CSS:
body, html {
margin: 0;
}
.container {
background: orange;
height: 2000px;
}
.banner {
width: 100%;
height: 400px;
background: white;
}
.float {
display: none;
width: 50px;
height: 50px;
background: red;
position: fixed;
top: 100px;
right: 100px;
/* this transition makes float travel high in banner when scrolling up */
/* transition: transform .3s linear; */
}
JS:
var float = document.querySelector('.float');
if (float) {
// init position
onScroll();
// check on scroll
window.addEventListener('scroll', onScroll);
}
function onScroll() {
var banner_height = 400;
var float_topCss = 100;
var float_height = 50;
if (window.scrollY < banner_height) {
position = 0;
// center vertically in banner
position += banner_height / 2;
position -= float_height / 2;
// account for current scroll
position -= window.scrollY;
// minus difference of top css value
position -= float_topCss;
float.style.transform = "translate3d(0,"+position+"px,0)";
}
else {
float.style.transform = "translate3d(0,0,0)";
}
float.style.display = 'block';
}
这是你要找的结果吗?
var float = document.querySelector('.float');
if (float) {
// init position
onScroll();
// check on scroll
window.addEventListener('scroll', onScroll);
}
function onScroll() {
var banner_height = 400;
if (window.scrollY < banner_height) {
float.classList.remove('sticky');
}
else {
float.classList.add('sticky');
}
}
body, html {
margin: 0;
}
.container {
background: orange;
height: 2000px;
position: relative;
}
.banner {
width: 100%;
height: 400px;
background: white;
}
.float {
display: inline-block;
width: 50px;
height: 50px;
background: red;
position: absolute;
top: 100px;
right: 100px;
float: right;
transition: transform .3s linear;
}
.float.sticky {
top: -50px;
transform: translateY(150px);
position: sticky;
}
<div class="container">
<div class="banner"></div>
<div class="float">Floating Element</div>
</div>