【问题标题】:Container with lots of content starts at a specific height, grows to fit content, and then shrinks on clicks包含大量内容的容器从特定高度开始,增长以适应内容,然后在点击时缩小
【发布时间】:2021-10-04 00:40:41
【问题描述】:

我正在尝试制作一个包含一些文本和图像的容器,并以特定大小开始,例如 48 像素。单击后,我希望容器增长以适应内容,然后单击第二次将缩小到 48px。主要问题是我不想为全尺寸容器设置高度,我希望容器自动调整大小以适应内容。

我已经想出了如何以全尺寸开始博客、缩小和重新增长,但我无法想出让它从小开始、增长和缩小的方法。

const hoistingId = document.getElementById('hoisting')

function enlargeBlogItem() {
    if(hoistingId.style.height===''){
        hoistingId.style.height = '3rem';
    } else {
        hoistingId.style.height = '';
    }
}

hoistingId.addEventListener('click', enlargeBlogItem)

【问题讨论】:

  • 你能设置一个包含你的代码的沙箱吗?

标签: javascript html css


【解决方案1】:

您可以在父元素上使用overflow: hidden; 以确保子元素在父元素内部并且不重叠,然后使用JavaScript 函数来处理大小更改。属性attr-small 用于存储height 的原始值。通过从父样式中删除 height 属性,它将默认包装子样式。

function toggleSize(el){

  const originalSize = el.getAttribute('attr-small');
  
  if(el.style.height === originalSize) {
    el.style.removeProperty('height');
  } else {
    el.style.height = originalSize;
  }
}
#container {
  border: 1px solid;
  width: 200px;
  overflow: hidden;
}

#container:hover {
  cursor: pointer;
}

.foo {
  width: 90px;
  height: 90px;
  background-color: red;
  display: inline-block;
  margin-left: 5px;
  margin-top: 5px;
}
<div id='container' onclick='toggleSize(this)' attr-small='48px' style='height:48px;'>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-12
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多