dw DIV+CSS实现图片自动切换?

html-css06

dw DIV+CSS实现图片自动切换?,第1张

完全可以,用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

}

效果图;

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

<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

既然楼主的问题竟然一年没找到满意答案……

不才刚刚开始学css3,愿意跟楼主分享一下图片切换心得。 如果楼主现在已经找到了解决方案,那请楼主无视我的答案。

首先,lp52761十五级大神的答案貌似不是很确切,其实css3+html5非常强大,基本上可以脱离js,除非要做出能响应移动设备触屏事件的网站,或者我的观点也落伍了,html5+css3也可以做出触屏响应特效。

我看csdn右侧图片切换有点类似opacity的变化,那么楼主不妨用keyframes方法在opacity上做文章;例如:

先定义一个keyframe

@keyframes qiehuan {

30%{opacity:1}

60%{opacity:0}

}

之后为图片容器做一个类:

.container{

/*这里长宽高边框边距之类的东西你自己随便写。*/

}

然后为你的图片们定义专属类:

.tupianmen{

position:absolute

//此处调用keyframe方法

animation:qiehuan 20s infinite

opacity:0

}

然后用css3独有的nth-child选择器来选择你要切换的图片

img:nth-child(4){animation-delay:0s}

img:nth-child(3){animation-delay:5s}

img:nth-child(2){animation-delay:10s}

img:nth-child(1){animation-delay:15s}

接下来你就可以写html了:

<!DOCTYPE html>

<html>

...... 略掉杂七杂八的东西......

<div class="container">

<img class="tupianmen" src="你的图片1" />

<img class="tupianmen" src="你的图片2" />

<img class="tupianmen" src="你的图片3" />

<img class="tupianmen" src="你的图片4" />

</div>

</html>

写完之后保存,查看效果如何

对了,差点忘了,如果用不同浏览器的话,可能需要简单更改一下keyframe或者animation的前缀,比如加一个-webkit-才行。

望采纳。。。