为了账号安全,请及时绑定邮箱和手机立即绑定

绝对定位的动画子 div 超出了其父级的边界,如何修复?

绝对定位的动画子 div 超出了其父级的边界,如何修复?

侃侃无极 2024-01-11 16:38:26
我正在对父 div 中绝对定位的子 div 的左侧位置进行动画处理。动画虽然确实有效,但当子 div 达到 50% ( 时50% {left:100%;},它会超出其父级的边界。A.) 为什么它只发生在 left: 100% 而不是 0% 时?B.) 如何让子项在父项内移动 - 不离开父项右侧?这是我的代码:#parent {  border:1px solid red;  width:500px;  height:200px;  margin:100px auto;  position:relative;}/* The element to apply the animation to */#child {  width:100px;  height:100px;  border:1px solid blue;  position:absolute;  -webkit-animation:animatedPos 20s linear infinite;  -o-animation:animatedPos 20s linear infinite;  -moz-animation:animatedPos 20s linear infinite;  animation:animatedPos 20s linear infinite;}/* The animation code */@-webkit-keyframes animatedPos {  0% {left:0%;}  50% {left:100%;}  100% {left:0%;}}@-o-keyframes animatedPos {  0% {left:0%;}  50% {left:100%;}  100% {left:0%;}}@-moz-keyframes animatedPos {  0% {left:0%;}  50% {left:100%;}  100% {left:0%;}}@keyframes animatedPos {  0% {left:0%;}  50% {left:100%;}  100% {left:0%;}}<div id="parent">  <div id="child"></div></div>
查看完整描述

4 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

改变


@keyframes animatedPos {

  0% {left:0%;}

  50% {left:100%;}

  100% {left:0%;}

}


*{

  box-sizing:border-box;

}

@keyframes animatedPos{

  0%{

    left:0;

  }

  50%{

    left:calc(100% - 100px);

  }

  100%{

    left:0;

  }

}


查看完整回答
反对 回复 2024-01-11
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

#parent {

  border:1px solid red;

  width:500px;

  height:200px;

  margin:100px auto;

  position:relative;

}


#uncle {

  border:0px solid silver;

  width:400px;

  height:200px;

  margin:0px auto;

  position:absolute;

}


/* The element to apply the animation to */

#child {

  width:100px;

  height:100px;

  border:1px solid blue;

  position:absolute;

  -webkit-animation:animatedPos 20s linear infinite;

  -o-animation:animatedPos 20s linear infinite;

  -moz-animation:animatedPos 20s linear infinite;

  animation:animatedPos 20s linear infinite;

}


/* The animation code */

@-webkit-keyframes animatedPos {

  0% {left:0%;}

  50% {right:100%;}

  100% {left:0%;}

}


@-o-keyframes animatedPos {

  0% {left:0%;}

  50% {left:100%;}

  100% {left:0%;}

}


@-moz-keyframes animatedPos {

  0% {left:0%;}

  50% {left:100%;}

  100% {left:0%;}

}


@keyframes animatedPos {

  0% {left:0%;}

  50% {left:100%;}

  100% {left:0%;}

}

<div id="parent">

<div id="uncle">

  <div id="child"></div>

</div>

</div>

这是一种解决方法,添加其他 Div(uncle) 减去动画宽度。该问题是由于使用轴移动的动画仅考虑一个点,而不是动画宽度。

应该是跨浏览器的。


查看完整回答
反对 回复 2024-01-11
?
喵喔喔

TA贡献1735条经验 获得超5个赞

您应该考虑子项的宽度并将其从 50% 减少。



查看完整回答
反对 回复 2024-01-11
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

您可以如下设置 50%。80% 使用父级和子级指定的宽度计算 ((500px-100px)/500px)


@keyframes animatedPos {

 0% {

  left: 0%;

 }

 50% {

  left: 80%;

 }

 100% {

  left: 0%;

 }

}


查看完整回答
反对 回复 2024-01-11
  • 4 回答
  • 0 关注
  • 47 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信