继续this example,我想集中在顶部div中的图像,因此,当页面滚动时,图像的中心总是出现在它上面。如何在无位置的div内裁剪/居中:相对?
为了实现这一点,我需要调整顶部div,而不是仅仅移动它。但是当我调整大小时,图像会溢出div,除非我使用overflow:hidden。问题是,溢出:隐藏only works与位置:相对。但是这打破了整个布局。
我该如何将图像居中顶部的div,仍然让它滚动像here?
HTML
<body onscroll='scroll(event)'>
<div class='top' id='top'><img src='http://www.vejanomapa.net.br/wp-content/uploads/2013/03/Maria-Fuma%C3%A7a-em-Tiradentes-MG.jpg'></div>
<div class='bottom' id='bottom'>
<div class='menu'>Menu</div>
<div class='main'><img src='http://tvulavras.com.br/wp-content/uploads/2017/04/maria-fuma%C3%A7a.jpg'></div>
</div>
</body>
的JavaScript
function scroll(e) {
var T = document.getElementById('top');
var B = document.getElementById('bottom');
var imgH = T.clientHeight; // header image height
var hH = 200; // fixed header height
if (imgH-e.pageY > hH) { // image is scrolling
T.classList.remove('active')
T.style.top = '-'+e.pageY+'px';
T.style.position = 'sticky';
B.style['margin-top'] = '0';
} else { // image should remain fixed
T.classList.add('active')
T.style.top = '-'+(imgH-hH)+'px';
}
}
CSS
html, body {
margin:0;
}
body {
overflow-y:scroll;
overflow-x:hidden;
}
img {
display:block;
}
.top {
background:#FCC;
display:block;
top:0;
position: sticky;
}
.active{
position: fixed;
}
.active ~ .bottom {
margin-top: 386px;
padding-left: 100px;
}
.active ~ .bottom .menu {
position: fixed;
top: 200px;
bottom: 0;
left: 0;
}
.bottom {
display:flex;
min-height:1500px;
background:#CFC;
}
.menu {
min-width:100px;
background:#CCF;
}
你能够把它添加到给定的jsfiddle例子,并使其发挥作用?我不能。 – Rodrigo
是 - 您可能遇到的问题是它设置为显示:块,宽度和高度未定义。如果你给它一些高度和宽度的规格,它将居中。 – yoursweater
你能提供一个工作的例子吗?问题不仅仅在于影像的中心位置,而是以影像为中心,以前的想法继续发挥作用。 – Rodrigo