javascript - 暂停交替的 css 动画并返回到它的原点

标签 javascript css css-animations

jQuery( ".button" ).click(function() {

  // STOP BOUNCING SMOOTHLYY
	$('.button').on('animationiteration webkitAnimationIteration', function () {
		var $this = $(this);
		$this.removeClass('loading');
	})

});
.button{
	position: absolute;
	top: calc(50vh - 10px);
	left: calc(50vw - 10px);

	height: 100px;
	width: 100px;

	border-radius: 100%;
	background-color: green;

	display: inline-block;
	cursor: pointer;
}

.loading{
	animation: bouncing 1s ease infinite alternate;
	animation-fill-mode: forwards;
}

@keyframes bouncing{
	from {transform: translateY(0);}
	to {transform: translateY(-100px);}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button loading"></div>

用 css 交替动画(变换:translateY)动画的弹跳球。我希望球在单击时停止移动并返回到其初始位置(可能会平滑缓和)。

css好像不知道动画在哪,那就没法回原点了。您是否有其他解决方案来实现这一目标?

最佳答案

您可以使用 getComputedStyle()。在 jQuery 中,您可以通过 .css() 来完成。

The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties.

对于CSS,让我们稍微修改一下。使默认行为暂停(animation-play-state: paused)并为 .loading 将其设置为运行。暂停的时刻是您获得计算样式来处理它的时候。

jQuery 中,动画将暂停,然后 CSS 变换(即 matrix())将被存储并应用于元素,旁边是transition 和将设置为 none 的动画 最后,经过一些延迟后,它将运行一个函数来应用转换,以便将元素带回起始位置。

jQuery( ".button" ).click(function() {

    $this = $(this);
    $this.removeClass('loading');
    computedTransform = $this.css("transform");

    $this.css({"transform": computedTransform, "transition": "0.86s", "animation": "none"}).delay(20).queue(function() { 
        $this.css("transform", "matrix(1, 0, 0, 1, 0, 0)")
  });

});
.button{
    position: absolute;
    top: calc(50vh - 10px);
    left: calc(50vw - 10px);
    height: 100px;
    width: 100px;
    border-radius: 100%;
    background-color: green;
    display: inline-block;
    cursor: pointer;
    animation: bouncing 1s ease infinite alternate forwards paused;
}

.loading {
    animation-play-state: running;
}

@keyframes bouncing{
    from {transform: translateY(0);}
    to {transform: translateY(-100px);}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button loading"></div>

关于javascript - 暂停交替的 css 动画并返回到它的原点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57873815/

相关文章:

javascript - HTTP 事件收集器 : How to send logs to Splunk Cloud from command line using curl?

Javascript 将来自 5 个来源的内容随机放入 3 个 div,且不重复

javascript - 使用jquery点击下拉菜单

css - 背景放大动画

javascript - 获取拖动元素抛出时的距离和时间值

ios - -webkit-animation-play-state 不适用于 iOS 8.1(可能也更低)

javascript - js函数调用需要帮助

javascript - Jquery弹出对话框更新多行记录?

css - 如何获得最大内容宽度值的一半?

html - 在某一行(inline-block)无序列表后插入一个中断