🪗 HTML+CSS 实现手风琴效果(无JS代码)

2024/12/30

function ListRender() {
  const data = [
    {
      q: 'Hello',
      a: 'Coding...'
    },
  ]

  return (
    <div className="list">
      {data?.map((data, index) => (
        <label className="faq-item" htmlFor={`item-checkbox-${index}`}>
          {/* 用于触发点击效果 */}
          <input hidden id={`item-checkbox-${index}`} type='checkbox' className='item-checkbox' />

          <div className='item-content'>
            <div className="faq-q">{data.q}</div>
            <div className="faq-a">
              <div className="faq-a-wrapper">{data.a}</div>
            </div>
          </div>
        </label>
      ))}
    </div>
  )
}

// css
.faq-item {
  cursor: pointer;
  position: relative;
  
  .item-checkbox {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;

    // 点击后的样式
    &:checked ~ .item-content .faq-a {
      grid-template-rows: 1fr;
    }
  }

  .item-content {

    .faq-q {
      line-height: 22px;
      font-size: 16px;
      font-weight: 500;
      padding: 4px 0;
    }

    .faq-a {
      // 0fr 为了让内容收起时高度为0
      display: grid;
      transition: 0.3s;
      grid-template-rows: 0fr;

      .faq-a-wrapper {
        overflow: hidden;  // 超出部分隐藏
        margin-top: 0.8rem;

        color: #646669;

        font-size: 16px;
        font-weight: 400;
        line-height: 22.4px;

        white-space: pre-wrap;
      }
    }
  }
}