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

我正在对父 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>


侃侃无极
浏览 113回答 4
4回答

紫衣仙女

改变@keyframes animatedPos {&nbsp; 0% {left:0%;}&nbsp; 50% {left:100%;}&nbsp; 100% {left:0%;}}到*{&nbsp; box-sizing:border-box;}@keyframes animatedPos{&nbsp; 0%{&nbsp; &nbsp; left:0;&nbsp; }&nbsp; 50%{&nbsp; &nbsp; left:calc(100% - 100px);&nbsp; }&nbsp; 100%{&nbsp; &nbsp; left:0;&nbsp; }}

杨__羊羊

#parent {&nbsp; border:1px solid red;&nbsp; width:500px;&nbsp; height:200px;&nbsp; margin:100px auto;&nbsp; position:relative;}#uncle {&nbsp; border:0px solid silver;&nbsp; width:400px;&nbsp; height:200px;&nbsp; margin:0px auto;&nbsp; position:absolute;}/* The element to apply the animation to */#child {&nbsp; width:100px;&nbsp; height:100px;&nbsp; border:1px solid blue;&nbsp; position:absolute;&nbsp; -webkit-animation:animatedPos 20s linear infinite;&nbsp; -o-animation:animatedPos 20s linear infinite;&nbsp; -moz-animation:animatedPos 20s linear infinite;&nbsp; animation:animatedPos 20s linear infinite;}/* The animation code */@-webkit-keyframes animatedPos {&nbsp; 0% {left:0%;}&nbsp; 50% {right:100%;}&nbsp; 100% {left:0%;}}@-o-keyframes animatedPos {&nbsp; 0% {left:0%;}&nbsp; 50% {left:100%;}&nbsp; 100% {left:0%;}}@-moz-keyframes animatedPos {&nbsp; 0% {left:0%;}&nbsp; 50% {left:100%;}&nbsp; 100% {left:0%;}}@keyframes animatedPos {&nbsp; 0% {left:0%;}&nbsp; 50% {left:100%;}&nbsp; 100% {left:0%;}}<div id="parent"><div id="uncle">&nbsp; <div id="child"></div></div></div>这是一种解决方法,添加其他 Div(uncle) 减去动画宽度。该问题是由于使用轴移动的动画仅考虑一个点,而不是动画宽度。应该是跨浏览器的。

喵喔喔

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

陪伴而非守候

您可以如下设置 50%。80% 使用父级和子级指定的宽度计算 ((500px-100px)/500px)@keyframes animatedPos {&nbsp;0% {&nbsp; left: 0%;&nbsp;}&nbsp;50% {&nbsp; left: 80%;&nbsp;}&nbsp;100% {&nbsp; left: 0%;&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5