图标开始在屏幕中央过渡

时间:2019-02-28 10:53:46

标签: html css css3 css-animations

我试图使图标在过渡到左侧之前出现在屏幕中间。这是我目前的代码:

#courseIcon {
  position: relative;
  background: url(https://placehold.it/100x100);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  width: 100px;
  height: 100px;
  top: 0;
  left: 20%;
  margin-left: -125px;
}

/* ICON TRANSITION */
.moveIcon {
  -webkit-animation: moveIcon 2s;
  animation: moveIcon 2s;
  animation-fill-mode: backwards;
  animation-delay: 3s;
}

@-webkit-keyframes moveIcon {
  from {
    -webkit-transform: translateX(500px);
  }

  to {
    -webkit-transform: translateX(0px);
  }
}

@keyframes moveIcon {
  from {
    transform: translateX(500px);
  }

  to {
    transform: translateX(0px);
  }
}
<div id="courseIcon" class="moveIcon"></div>

目前,我刚刚设置了translatex: 500px,因为这大约是我正在查看的屏幕的一半。不管屏幕大小如何,有没有一种方法可以使过渡从页面的中央开始?这是我在fiddle中的代码。

谢谢您的时间。

2 个答案:

答案 0 :(得分:3)

  • 绝对位置#courseIcon
  • 使用transform / translate从屏幕中间开始
  • 使用transform/translate进行动画处理以提高GPU的平滑度
  • 删除from子句(不必要)
  • 要阻止animation完成重置,请使用animation-fill-mode: forwards

编辑:从calc排名计算中删除了animation。正如@TemaniAfif聪明地指出的那样,IE11不支持用calc()设置的转换值。

#courseIcon {
  position: absolute;
  background: url(https://placehold.it/100x100);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* ICON TRANSITION */
.moveIcon {
  -webkit-animation: moveIcon 2s;
  animation: moveIcon 2s;
  animation-fill-mode: forwards;
  animation-delay: 3s;
}

@-webkit-keyframes moveIcon {
  to {
    -webkit-transform: translate(-50vw, -50%);
  }
}

@keyframes moveIcon {
  to {
    transform: translate(-50vw, -50%);
  }
}
<div id="courseIcon" class="moveIcon"></div>

答案 1 :(得分:1)

您可以考虑使用left(或right),并且不需要任何复杂的计算:

function recase(str: string, lower: ?boolean): string {
  if (lower) {
    return str.toLowerCase();
  }

  return str.toUpperCase();
}
#courseIcon {
  position: absolute;
  background: url(https://placehold.it/100x100) center/contain no-repeat;
  width: 100px;
  height: 100px;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
}

/* ICON TRANSITION */
.moveIcon {
  animation: moveIcon 2s forwards 3s;
}

@keyframes moveIcon {
  to {
    left:0;
  }
}

body {
 overflow:hidden;
}

如果您需要更好的浏览器支持,也可以不使用<div id="courseIcon" class="moveIcon"></div>进行以下操作:

calc()
#courseIcon {
  position: absolute;
  background: url(https://placehold.it/100x100) center/contain no-repeat;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
}

/* ICON TRANSITION */
.moveIcon {
  animation: moveIcon 2s forwards 3s;
}

@keyframes moveIcon {
  to {
    left:0;
    transform:translate(0%,-50%);
  }
}

body {
 overflow:hidden;
}