【问题标题】:Two containers sharing vertical height dynamically两个容器动态共享垂直高度
【发布时间】:2017-07-25 06:11:30
【问题描述】:

我有两个容器需要共享其父级的高度,但第二个容器是按需动态添加的。两个容器中可能有很多内容,因此必须提供滚动的机会。

我有一个 50/50 共享的可行解决方案,但我想知道是否可以动态共享高度。

.wrapper__container {
  display: flex;
  height: 100%;
  max-width: 100%;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inside__container {
  flex: 0 0 100%;
  max-width: 100%;
  overflow-y: auto;
}

部分包装组件渲染方法:

render() {
  const maxHeight = this.state.showDetails ? '50%' : '100%';
  const minHeight = this.state.showDetails ? '50%' : '100%';
  return (
    <div className="wrapper__container">
      <Config 
        itemsGreen={this.state.itemsGreen}
        itemsRed={this.state.itemsRed}
        changeItemCount={this.changeItemCount}
      />
      <Container
        itemCount={this.state.itemsGreen}
        className="inside__container"
        style={{
          backgroundColor: 'green',
          maxHeight,
          minHeight
        }}
        onClick={this.handleClick}
      />
      {this.state.showDetails && <Container
        itemCount={this.state.itemsRed}
        className="inside__container"
        style={{ 
          backgroundColor: 'tomato',
          maxHeight,
          minHeight
        }}
      />}
    </div>
  )
}  

我设置了一个codepen,您可以在其中更改项目数以测试行为。单击绿色容器以显示红色容器。

至少将绿色容器的最大高度限制为 50% 并让红色容器占据其余部分是一个很好的解决方案。例如,如果绿色仅占 20%,则红色可以占 80%。

在一个完美的世界中,这应该可以在没有 js 计算的情况下实现,但如果有人有计算这个的想法(只有 react/vanilla)。

目标浏览器是IE11。

编辑:添加了一个新的Pen,该Pen 已损坏,但在只有少数项目时会显示所需的灵活行为。

【问题讨论】:

  • 要滚动哪个元素?您必须选择 一个 否则这无法用 CSS 解决。
  • 它们都应该是可滚动的,我需要计算高度才能完成这项工作吗?

标签: javascript html css reactjs


【解决方案1】:

每次渲染外部容器时,您需要获取容器的高度并将其除以 2,然后将该数字用作每个内部 div 的高度。像这样(使用jquery):

var $two = $('<div id="two"></div>');
var $three = $('<div id="three"></div>');
$('#container').append($two);
$('#container').append($three);
var h = $('#one').height();
console.log((h/2)-1)
if($('#two').height() < ((h/2)-1)) {
  $('#three').height( ( h-$('#two').height() ) - 1 );
} else {
   $('#two').height((h/2)-1);
   $('#three').height((h/2)-1);
}

【讨论】:

  • 我是不是已经磨损了,或者这个计算是否也让我得到了 50/50 的灵魂。我想计算相互依赖的份额。
  • 我有一个 50/50 共享的可行解决方案,但我想知道是否可以动态共享高度。 ....如果绿色,例如,只有 20%,红色可以占 80%。什么不清楚?所以我可以改进这个问题。
  • 我已经编辑了答案以更好地满足您的问题。
猜你喜欢
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 2016-06-28
  • 1970-01-01
  • 2014-02-01
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多