css背景图片每3秒自动切换

html-css019

css背景图片每3秒自动切换,第1张

<div class="change">

</div>

<style>

.change {

animation: change 9s steps(1) infinite

background-repeat: no-repeat

background-position: center center

background-size: 100% auto

width: 200px

height: 100px

}

@keyframes change {

0% {

background-image: url(https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png)

}

33% {

background-image: url(https://www.duhongwei.site/img/201809/s1.png)

}

66% {

background-image: url(https://p4.ssl.qhimg.com/t01fcaa9d8a4d24b5f1.png)

}

}

</style>

纯 css 每3秒播一张图片。9s是总共时间,如果是4张图片这里写 12s

完全可以,用css的重复播放动画的功能实现自动切换。

做了个小例子,你可以看看,基本的思路就这样了,效果还比较不错啦。这个思路还可以用来作为图片滚动播放的例子呢。

body部分代码:

<body>

<div id="box1">

<div id="box2">

<img src="https://www.baidu.com/img/bd_logo1.png">

<img src="https://www.baidu.com/img/bd_logo1.png">

<img src="https://www.baidu.com/img/bd_logo1.png">

<img src="https://www.baidu.com/img/bd_logo1.png">

</div>

</div>

</body>

css的代码:

*{

padding:0

margin:0

}

html,body{

overflow-x:hidden

overflow-y:auto

}

#box1{

position:relative

width:500px

height:450px

margin:0 auto

background:red

overflow:hidden

}

#box2{

float:left

width:2000px

height:450px

animation:box2 2s both linear infinite

-webkit-animation:box2 2s both linear infinite/* Safari and Chrome */

}

#box2:hover {

animation-play-state: paused

}

@keyframes box2

{

from {

margin-left:0

}

to {

margin-left:-1500px

}

}

@-webkit-keyframes myfirst /* Safari and Chrome */

{

from {

margin-left:0

}

to {

margin-left:-1500px

}

}

img{

float:left

width:500px

height:450px

}

效果图;

好像时间间隔设置太短了,可以把动画播放的时间延长一点。

感觉自己总是混淆css各种动画效果,所以再这里总结一下

1. transition ,所在元素块样式变动时启动,可用于样式变动时 产生过渡动画效果

| transition-property | 规定设置过渡效果的 CSS 属性的名称。 |

| transition-duration | 规定完成过渡效果需要多少秒或毫秒。 |

| transition-timing-function | 规定速度效果的速度曲线。 |

| transition-delay | 定义过渡效果何时开始。 |

2. tranform :用于平移,旋转,缩放,透视

语法

animation-name 规定需要绑定到选择器的 keyframe 名称。

animation-duration规定完成动画所花费的时间,以秒或毫秒计。

animation-timing-function规定动画的速度曲线。

animation-delay规定在动画开始之前的延迟。

animation-iteration-count规定动画应该播放的次数。

animation-direction规定是否应该轮流反向播放动画。

animationname 必需。定义动画的名称。

keyframes-selector 必需。动画时长的百分比。值:0-100%,from(与 0% 相同),to(与 100% 相同)

css-styles 必需。一个或多个合法的 CSS 样式属性。

4.@media :可以根据屏幕大小响应式改变样式

接下来利用transition和transfrom实现一个简单的翻牌效果,先看效果