用css如何实现背景图片的自动替换?

html-css0142

用css如何实现背景图片的自动替换?,第1张

哈哈,这几楼的回答都不太正确,css可以自己完成图片的自动切换,不需要什么js辅助。人家楼主问的如何用css来实现,你搞的那个什么用js来实现,答非所问,还弄个专业回答,逗子终结者?

css有个执行简单动画的写法,比如animation。

我给你个例子:

#head-pic,#head-pic2{

width:145pxheight:145pxposition:absolute

top:200px

left:68px

z-index:2

border-radius:100px

-webkit-border-radius:100px

-moz-border-radius:100px

border:3px solid #fff

}

/*为浏览器兼容设置*/

@keyframes headpic-slider{

from{background:url(../images/head-pic.jpg)opacity:1.0}

to{background:url(../images/head-pic.jpg)opacity:0}

}

@keyframes headpic-slider2{

from{background:url(../images/head-pic2.jpg)opacity:0}

to{background:url(../images/head-pic2.jpg)opacity:1.0}

}

@-moz-keyframes headpic-slider{

from{background:url(../images/head-pic.jpg)opacity:1.0}

to{background:url(../images/head-pic.jpg)opacity:0}

}

@-moz-keyframes headpic-slider2{

from{background:url(../images/head-pic2.jpg)opacity:0}

to{background:url(../images/head-pic.jpg)opacity:1.0}

}

@-webkit-keyframes headpic-slider{

from{background:url(../images/head-pic.jpg)opacity:1.0}

to{background:url(../images/head-pic.jpg)opacity:0}

}

@-webkit-keyframes headpic-slider2{

from{background:url(../images/head-pic2.jpg)opacity:0}

to{background:url(../images/head-pic2.jpg)opacity:1.0}

}

@-o-keyframes headpic-slider{

from{background:url(../images/head-pic.jpg)opacity:1.0}

to{background:url(../images/head-pic.jpg)opacity:0}

}

@-o-keyframes headpic-slider2{

from{background:url(../images/head-pic2.jpg)opacity:0}

to{background:url(../images/head-pic2.jpg)opacity:1.0}

}

#head-pic{

animation:headpic-slider 20s linear infinite

-moz-animation:headpic-slider 20s linear infinite

-webkit-animation:headpic-slider 20s linear infinite

}

#head-pic2{

animation:headpic-slider2 20s linear infinite

-moz-animation:headpic-slider2 20s linear infinite

-webkit-animation:headpic-slider2 20s linear infinite

}

需要准备的材料分别有:电脑、浏览器、html编辑器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<style>标签中,输入css代码:

div{height: 80pxbackground: url(small3.png)}div:hover{background: url(small2.png)}。

3、浏览器运行index.html页面,此时div显示的背景图片是small3.png。

4、将鼠标移入div,此时背景图片自动变更成了small2.png。