侧边栏css动画-线条跟随鼠标

239 阅读1分钟

需求

实现侧边栏激活线条跟随鼠标移动效果

实现

  1. html
<div class="box">
  <div class="box-item">1</div>
  <div class="box-item">2</div>
  <div class="box-item">3</div>
  <div class="box-item">4</div>
</div>
  1. css
  • 绘制侧边线条

将侧边栏的线条固定到侧边;

.box{
  width: 30px;
  display: flex;
  flex-direction: column;
  &-item{
    width: 100%;
    height: 30px;
    padding: 10px;
    position: relative;
    border-left: 1px solid #000;
  }
}


  • 隐藏线条,鼠标经过显示

样式需要用到伪类;设置伪类宽高,通过height:0将线条隐藏;当鼠标经过时,设置height:100%展示线条

.box{
  width: 30px;
  display: flex;
  flex-direction: column;
  &-item{
    width: 100%;
    height: 30px;
    padding: 10px;
    // 鼠标跟随效果
    position: relative;
    border-left: 0px solid #000;

    &::before {
      content: "";
      position: absolute;
      top: 100%;
      left: 0%;
      width: 0%;
      height: 0%;
      border-left: 3px solid #000;
      transition: 0.1s all linear;
    }

    &:hover::before {
      height: 100%;
      top: 0%;
    }
  }
}
  • 实现线条跟随鼠标

使用兄弟选择器~,为伪类元素和鼠标移过设置css样式

    &:hover~&::before {
      top: 0%;
    }