【问题标题】:How to change the size of an element after each animation-iteratioin-count?如何在每次动画迭代计数后更改元素的大小?
【发布时间】:2013-12-02 03:46:40
【问题描述】:

假设,我的动画从 0%{left: 0%;bottom: 0%;} 到 100%{left: 100%; bottom: 0%;} 并将动画迭代计数设置为无限。

现在,当动画移动到结束点 (100%) 时,它会再次从 开始点 (0%) 开始。 现在我想要的是动画再次开始时并且它应该再次减小元素的大小假设默认大小为200 pixels width and 200 pixels height,因此减小的值等于负 10 像素,当动画元素的宽度和高度变为 0 像素时,它应该再次增加该元素的大小,因此增加的值等于加上 10 个像素。

这是demo,没有增加和减少元素。

【问题讨论】:

  • 元素大小是否已知?意思是你知道它的大小会在 x 次迭代后变为 0?
  • 从 200px 到 190px 和 180px 和 170px .... 最后 0 px 现在应该重新开始 200px 到 190px ,,,,

标签: javascript jquery css animation


【解决方案1】:

这可以清理,但基本上你可以监听animationStart 来捕获元素的初始大小,

$("#element").on("webkitAnimationStart", function(e) {
    var el = $(this);

    initialHeight = el.height();
    initialWidth = el.width();
});

...并监听animationIteration 以在每次迭代后更改元素的大小:

$("#element").on("webkitAnimationIteration", function(e) {
    var el = $(this),
        currentHeight = el.height(),
        currentWidth = el.width(),
        scaleStep = 10;

    if (currentHeight > 0 && currentWidth > 0) {
        el.height(currentHeight - scaleStep);
        el.width(currentWidth - scaleStep);
    }
    else {
        el.height(initialHeight);
        el.width(initialWidth);
    } 
});

DEMO

请注意,这仅适用于 webkit 浏览器。要支持其他浏览器,请查看本文中的浏览器兼容性部分:

http://www.sitepoint.com/css3-animation-javascript-event-handlers/

【讨论】:

  • 在演示中大小甚至没有减小。
  • 您使用的是 Chrome 还是 Safari?
【解决方案2】:

如果您的浏览器支持动画中的 steps() 和多个动画,您可以使用纯 CSS 解决方案。

@keyframes esize
{
0%{left: 0%; bottom: 0%;}
100%{left: 90%; bottom: 0%;}
}
@-webkit-keyframes esize
{
    0%{left: 0%; bottom: 0%;}
  100%{left: 90%; bottom: 0%;}
}
@-webkit-keyframes shrink
{
    0%{width: 200px; height: 200px;}
  100%{width: 0px; height: 0px;}
}
@keyframes shrink
{
    0%{width: 200px; height: 200px;}
  100%{width: 0px; height: 0px;}
}

#element{
    width: 200px;
    height: 200px;
    border-radius: 100%;
    background: #000;
    position: absolute;
    left: 0%;
    bottom: 0%;
    animation: esize 3s infinite, shrink 60s steps(20,end) infinite;
    -webkit-animation: esize 3s infinite, shrink 60s steps(20,end) infinite;
}

我已经把它变慢了,这样你就可以看到尺寸变化是一步一步完成的,而不是连续的

updated fiddle

【讨论】:

    猜你喜欢
    • 2019-01-04
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2021-10-17
    • 2018-11-03
    • 2018-01-01
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多