[英]Element transform transition between appearing 'relative' and 'fixed' not smooth
我有一個帶有橫幅( .banner
)和一個浮動元素( .float
)的頁面。
當用戶在查看橫幅的情況下滾動時,我希望.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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.