Recently, I saw that when my team partner realized the animation effect of expanding/unfolding the drop-down text box with unfixed height, it involved javascript to calculate the height of the drop-down box, and then realized the animation by setting the transition effect of height through CSS. In addition, when triggering the expansion/unfolding, Also through javascript to listen to the document click event to handle, I prefer to use CSS to achieve the following effect:

  • The CSS transform: rotate(-90deg) rotates elements to expand and fold them up
  • The parent element sets the tabIndex property and controls expansion and collapse with the: Focus selector

html:

<div class="select" tabIndex ="1"> <div class="select-inner"> I am a select</div> <div class="select-panel" <div class="select-option"> I am the first option </div> </div> </div>Copy the code

transform: rotate(-90deg)

Transform: Rotate (-90deg) of CSS can be used to achieve a similar effect

.select-panel {
  transform: rotateX(90deg)
  transform-origin: center 0;
  transition: transform .2s;
}
Copy the code

tabindex + :focus

The tabIndex attribute allows the element to get focus. After clicking on the element, the element gets focus, and you can control the style of the child element with the: Focus pseudo-class selector

.select:focus {
  .select-panel {
    transform: rotateX(0deg)
  }
}
Copy the code

Complete code, copy available

/ / HTML: <div class="select" tabIndex ="1"> <div class="select-inner"> I am a select</div> <div class="select-panel" Class ="select-option"> I'm the first option </div> <div class="select-option"> I'm the second option </div> <div class="select-option"> I'm the third option </div> <div class="select-option"> I am the fourth option </div> <div class="select-option"> I am the fifth option </div> </div> </div> // CSS: .select { position: relative; width: 250px; font-size: 12px; color: #606266; outline: none; &:focus { .select-inner { border-color: #409eff; &::after { transform: rotateZ(180deg) } } .select-panel { transform: rotateX(0deg) } } .select-inner { width: 100%; height: 36px; line-height: 34px; padding: 0 30px 0 10px; border-radius: 4px; border: 1px solid #dcdfe6; outline: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; &::after { content: ''; position: absolute; top: 15px; right: 10px; border: 6px solid #bbb; border-top-width: 7px; border-bottom: none; border-left-color: transparent; border-right-color: transparent; transform: rotateZ(0deg) transform-origin: center center; transition: transform .2s; } } .select-panel { position: absolute; top: 100%; left: 0; margin-top: 2px; padding: 10px 0; width: 100%; border-radius: 4px; box-shadow: 0 0 8px 0 rgba(0, 0, 0, .1); transform: rotateX(90deg) transform-origin: center 0; transition: transform .2s; .select-option { padding: 6px 10px; cursor: pointer; &:hover { color: #fff; background-color: #409eff; }}}}Copy the code