首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >CSS3滑动渐变动画-工作原理

CSS3滑动渐变动画-工作原理
EN

Stack Overflow用户
提问于 2018-09-19 03:07:56
回答 1查看 948关注 0票数 0

下面的代码不需要任何javascript代码就可以生成滑动渐变动画:

代码语言:javascript
复制
html {
  height: 100%
}

body {
  height: 100%;
  margin: 0
}

@keyframes loading {
  from {
    background-position: -5000% 0, 0 0
  }
  to {
    background-position: 5000% 0, 0 0
  }
}

.skeleton {
  height: 100%;
  animation-name: loading;
  animation-duration: 1.5s;
  animation-iteration-count: infinite;
  background-color: #fff;
  background-repeat: no-repeat;
  background-image: linear-gradient(90deg, hsla(0, 0%, 100%, 0), hsla(0, 0%, 100%, .8) 50%, hsla(0, 0%, 100%, 0)), linear-gradient(#e5e5e5 100%, transparent 0);
  background-size: 99% 100%;
}
代码语言:javascript
复制
<div class="skeleton"></div>

我尝试了一些属性,但仍然不明白它是如何工作的。特别是在将background-size: 99% 100%;改为background-size: 100% 100%;动画幻灯片时!

你能解释一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-19 06:21:15

我不知道你的浏览器是什么和它的版本。但在我的电脑上,如果是background-size: 100% 100%,动画将会停止。(实际上,background-position将被忽略)

这个技巧的想法是用background-position移动background-image (线性梯度)。(有关详细信息,请查看以下代码中的注释)

关于你的第二个问题,你应该参考这个答案CSS background-position ignored when using background-size。快速总结一下,如果background-size达到100%,就不能对background-position使用percent。这是因为背景中的图像没有可移动的空间。

如果你坚持使用100%的background-size。恐怕您必须使用绝对值。

顺便说一句,我已经升级了代码。现在看起来好多了。

代码语言:javascript
复制
html {
  height: 100%
}

body {
  height: 100%;
  margin: 0
}

@keyframes loading {/* original code */
  from {/* This is the position of image of the first frame */
    background-position: -5000% 0, 0 0
  }
  to {/* This is the pos of img of the last frame */
    background-position: 5000% 0, 0 0
  }
}

@keyframes betterLoading {
  0% {/* This is the position of image of the first frame */
    background-position: -5000% 0, 0 0
  }
  50% {
    /* This is the pos of img of a frame in the middle happening animation */
    /* If duration is 1s then the pos below will be at 0.5s */
    background-position: 5000% 0, 0 0
  }
  100% {/* This is the pos of img of the last frame */
    background-position: -5000% 0, 0 0
  }
}

.skeleton {
  height: 100%;
  animation-name: betterLoading;
  animation-duration: 1.5s;
  animation-iteration-count: infinite;
  background-color: #fff;
  background-repeat: no-repeat;
  background-image: linear-gradient(90deg, hsla(0, 0%, 100%, 0), hsla(0, 0%, 100%, .8) 50%, hsla(0, 0%, 100%, 0)), linear-gradient(green 100%, transparent 0);
  background-size: 99% 100%, cover;
}
代码语言:javascript
复制
<div class="skeleton"></div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52393135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档