css实现鼠标移上去div的四条边框出现的动画效果

394 阅读1分钟

实现效果

初始效果

image.png

鼠标移入

image.png

鼠标移出

以四边收入的方式消失

image.png

代码实现

结构

<div class="item">
    <i></i>
    <a href="products.html"><img src="static/images/products/item3.png" alt="" /></a>
    <p>Home Decoration</p>
</div>

样式

.item {
  width: 260px;
  height: 400px;
  border: 1px solid #e6e6e6;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
  transition: 0.4s;
  overflow: hidden;
}

/* 上边的线 */
.item:before {
  position: absolute;
  left: 0;
  top: 0;
  background: #d42829;
  content: "";
  width: 100%;
  height: 2px;
  box-sizing: border-box;
  transition: 0.4s;
  transform-origin: left top;
  z-index: 2;
  transform: scaleX(0);
}

/* 右边的线 */
.item:after {
  position: absolute;
  right: 0;
  top: 0;
  background: blue;
  content: "";
  width: 2px;
  height: 100%;
  box-sizing: border-box;
  transition: 0.4s;
  z-index: 2;
  transform-origin: left top;
  transform: scaleY(0);
}

.item:hover:before {
  transform: scaleX(1);
}

.item:hover:after {
  transform: scaleY(1);
  transition-delay: 0.4s;  /* 可以通过延时控制四条边按顺序出现 */
}

/* 下边的线 */
.item i:before {
  position: absolute;
  right: 0;
  bottom: 0;
  background: purple;
  content: "";
  width: 100%;
  height: 2px;
  box-sizing: border-box;
  transition: 0.4s;
  transform-origin: right top;
  transform: scaleX(0);
  z-index: 2;
}

/* 左边的线 */
.item i:after {
  position: absolute;
  left: 0;
  bottom: 0;
  background: black;
  content: "";
  width: 2px;
  height: 100%;
  box-sizing: border-box;
  transition: 0.4s;
  transform-origin: left bottom;
  transform: scaleY(0);
  z-index: 2;
}

.item:hover i:before {
  transform: scaleX(1);
  transition-delay: 0.8s;
}

.item:hover i:after {
  transform: scaleY(1);
  transition-delay: 1.2s;
}