我正在研究一种本质上类似于老虎机的布局。它的每个子项都是文本,并且布局是响应式的(因此在不同的分辨率下,子项的文本可能会或可能不会换行到多行,从而改变高度)。
布局将有一个可见的“视口(viewport)”,一次显示 3 个元素。为了使“视口(viewport)”不会四处移动,所有 child 都需要具有相同的高度。这让我想到了 2 条不同的路线,但我都做不到。
- 使用显示:flex。使用列布局,您可以将它们全部堆叠起来。这个问题是,我不认为你可以让所有的 child 都有相同的高度,除非你在 flex 容器上指定一个计算高度(因此,你必须使用 js 来计算所有 flex child 的最大高度)
- 使用显示:网格。开箱即用,您可以使用网格使所有 child 具有相同的高度。问题是,如何 overflow hidden 以确保您在老虎机的“视口(viewport)”中一次只显示 3 个?
如果没有 js 计算,这种布局可能是不可能的,但由于它必须完全响应,我不想在每次调整窗口大小时都重新计算。任何人都可以想出一种使用纯 css 来做到这一点的方法吗?
我做了一个 fiddle 来展示一个简单的实现。 “视口(viewport)”是红色框,每个元素都在蓝色框内。在现实世界中,我会把所有东西都隐藏在红框之外,并且不想在任何容器上专门设置高度。
var scroll = document.getElementById('scroll');
var wrapper = document.getElementById('wrapper');
scroll.addEventListener('click', function() {
wrapper.classList.toggle('scrolled');
});
.example {
display: flex;
}
.container {
height: 90px;
width: 300px;
outline: 1px solid red;
z-index:1;
}
.wrapper {
display: flex;
flex-direction: column;
transition-property: transform;
transition-duration: 500ms;
}
.wrapper.scrolled {
transform: translateY(-300px);
}
.inner {
outline: 1px solid blue;
flex-grow: 1;
height: 30px;
}
.buttons {
margin-right: 3em;
}
<div class="example">
<div class="buttons">
<button id="scroll">Scroll</button>
</div>
<div class="container">
<div id="wrapper" class="wrapper">
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
<div class="inner">Some text</div>
</div>
</div>
</div>
最佳答案
嘿,所以我想我明白了你的意思,并设计了一个“老虎机”机制,它使用 vh 缩放其内部和外部对象。
所以容器对象会有类似...
.container {
width: 300px;
height: 90vh;
outline: 1px solid red;
z-index:1;
overflow: hidden;
}
...内部对象会有类似...
.inner {
outline: 1px solid blue;
flex-grow: 1;
height: 30vh;
}
我还调整了 Javascript 滚动,以根据滚动对象的滚动量进行调整。这可以使用类似计时器而不是按钮的东西来自动化:
var scroll = document.getElementById('scroll');
var wrapper = document.getElementById('wrapper');
var innerArray = document.getElementsByClassName('inner');
var innerNum = 1; // Start at the second element
scroll.addEventListener('click', function() {
if (innerNum == innerArray.length-2) { // Check to see if the last item has been scrolled to
innerNum = 0; // Scroll back to the first item if it has
}
//wrapper.classList.toggle('scrolled');
innerArray[innerNum].scrollIntoView({
behavior: 'smooth'
});
innerNum++;
});
Here是演示示例的代码笔。如果您愿意,我可以进一步澄清代码。如果我对您的目标有误解,我深表歉意!
关于javascript - 创建一个具有动态高度子项的 "slot machine",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47341452/