当父元素具有可见性时,是否会运行CSS3动画:隐藏?

前端之家收集整理的这篇文章主要介绍了当父元素具有可见性时,是否会运行CSS3动画:隐藏?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我定义了 CSS3 animation(以及相关的@keyframes):
animation: myAnimation 2.1s cubic-bezier(0.65,0.815,0.735,0.395) infinite;

即使你看不到它,如果父元素具有可见性:隐藏,这个动画是否正在运行(和消耗资源)?

解决方法

是的,即使父容器具有可见性,动画也会继续运行:隐藏,因为该元素仍然存在且仅隐藏.在下面的代码片段中,您可以验证.output div的内容,以查看它是否继续运行并且marginLeft不断变化.
window.onload = function() {
  var animEl = document.querySelector('.animated');
  var outputEl = document.querySelector('.output');
  window.setTimeout(function() {
    outputEl.textContent = 'Margin left when visibility becomes hidden: ' + window.getComputedStyle(animEl).marginLeft;
    document.querySelector('.wrapper').style.visibility = 'hidden';
    window.setTimeout(function() {
      outputEl.textContent = 'Margin left when visibility becomes visible: ' + window.getComputedStyle(animEl).marginLeft;
      document.querySelector('.wrapper').style.visibility = 'visible';
    },1000);
  },1000);
}
.wrapper{
  white-space: nowrap;
}
.wrapper > div {
  display: inline-block;
  height: 100px;
  width: 100px;
  border: 1px solid;
}
.animated {
  animation: move 3s linear infinite;
}
@keyframes move {
  to {
    margin-left: 300px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='wrapper'>
  <div class='animated'></div>
  <div class='sibling'></div>
</div>
<div class='output'></div>

根据W3C Spec,只设置display:none终止正在运行的动画(我们可以将其视为不会启动动画).

Setting the display property to ‘none’ will terminate any running animation applied to the element and its descendants. If an element has a display of ‘none’,updating display to a value other than ‘none’ will start all animations applied to the element by the ‘animation-name’ property,as well as all animations applied to descendants with display other than ‘none’.

正如您在下面的代码段中所看到的,当显示设置为none时动画终止,并在设置回块时从第一个关键帧重新启动.

window.onload = function() {
  var animEl = document.querySelector('.animated');
  var outputEl = document.querySelector('.output');
  window.setTimeout(function() {
    outputEl.textContent = 'Margin left when display becomes none: ' + window.getComputedStyle(animEl).marginLeft;
    document.querySelector('.wrapper').style.display = 'none';
    window.setTimeout(function() {
      outputEl.textContent = 'Margin left when display becomes block: ' + window.getComputedStyle(animEl).marginLeft;
      document.querySelector('.wrapper').style.display = 'block';
    },1000);
}
.wrapper {
  white-space: nowrap;
}
.wrapper > div {
  display: inline-block;
  height: 100px;
  width: 100px;
  border: 1px solid;
}
.animated {
  animation: move 3s linear infinite;
}
@keyframes move {
  to {
    margin-left: 300px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='wrapper'>
  <div class='animated'></div>
  <div class='sibling'></div>
</div>
<div class='output'></div>
原文链接:https://www.f2er.com/css/216030.html

猜你在找的CSS相关文章