首页 > 解决方案 > 悬停时一个元素的 CSS 过渡不平滑,但当鼠标移开时是平滑的

问题描述

我有以下 CSS 和 HTML。问题是,当鼠标移到按钮上时,红色矩形会闪烁到中心而不是平滑地移动到中心。这很奇怪,因为当鼠标从按钮上移开时,它会慢慢向后移动。如何使红色矩形平滑地移动到中心?

  .btn {
    position: relative;
    display: inline-block;
    padding: 30px 45px;
    margin: 80px;
    cursor: pointer;
  }
  .btn .rect {
    transition: all 0.5s linear;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    position: absolute;
  }
  .btn .top-left {
    top: -10px;
    left: -10px;
  }
  .btn .bottom-right {
    bottom: -10px;
    right: -10px;
  }
  .red-translucent {
    background-color: red;
  }
  .blue-translucent {
    background-color: blue;
  }
  .btn-text {
    z-index: 99999;
    position: relative;
    font-family: Arial;
  }
  .btn:hover .rect {
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
  <div class='btn'>
    <span class='btn-text'>button</span>
    <div class='rect top-left blue-translucent'></div>
    <div class='rect bottom-right red-translucent'></div>
  </div>

标签: csscss-transitions

解决方案


出于某种原因,它不适用于bottom: -10pxand right: -10px。我不确定这是否与我的代码有关,或者这是否是浏览器问题,但简单的解决方法是改用topandleft属性:

  .btn {
    position: relative;
    display: inline-block;
    padding: 30px 45px;
    margin: 80px;
    cursor: pointer;
  }
  .btn .rect {
    transition: all 0.5s linear;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    position: absolute;
  }
  .btn .top-left {
    top: -10px;
    left: -10px;
  }
  .btn .bottom-right {
    top: 10px;
    left: 10px;
  }
  .red-translucent {
    background-color: red;
  }
  .blue-translucent {
    background-color: blue;
  }
  .btn-text {
    z-index: 99999;
    position: relative;
    font-family: Arial;
  }
  .btn:hover .rect {
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
  <div class='btn'>
    <span class='btn-text'>button</span>
    <div class='rect top-left blue-translucent'></div>
    <div class='rect bottom-right red-translucent'></div>
  </div>


推荐阅读