css js 实现图片动态切换

来源:互联网 发布:淘宝直播的运营怎么做 编辑:程序博客网 时间:2024/06/06 19:03

在网易云音乐首页有一个图片展示区,觉得不错,就尝试照着做了。

因为只初步接触css和javascript,所以最后我只完成一小部分功能,就是点击图片区域,图片向左切换(还不知道怎么自动切换= = 设想是不是要用到js的时钟),实际上只是用到了css的animation属性和js对animationed事件的监听。——css动画结束之后又会回到原位置,好讨厌这点——。

下面是代码:

<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title><style>img{position: absolute;}#img1{z-index: 10;width: 540px;height: 190px;top: 10px;left: 0px;/*animation: movetoright 1s 3s;*/}#img2{z-index: 30;width: 540px;height: 200px;top: 0px;left: 110px;/*animation:movetoleft 1s 3s;*/}#img3{z-index: 20;width: 540px;height: 190px;top: 10px;left: 220px;/*animation: movetomiddle 1s 3s;*/}@keyframes movetoleft{from{top: 0px;left: 110px;}to{top: 10px;left: 0px;height: 190px;z-index: 10;}}@keyframes movetoright{from{top: 10px;left: 0px;}to{top: 10px;left: 220px;height: 190px;z-index: 20;}}@keyframes movetomiddle{from{top: 10px;left: 220px;}to{top: 0px;left: 110px;height: 200px;z-index: 30;}}</style><script>function clicked(){//alert("1");document.getElementById("img1").style.animation="movetoleft 1s";document.getElementById("img2").style.animation="movetoleft 1s";document.getElementById("img3").style.animation="movetomiddle 1s";var i=0;var e = document.addEventListener("animationend",function(){//alert("结束了?");i++;if(i == 3){var img1src =document.getElementById("img1").getAttribute("src");document.getElementById("img1").src=document.getElementById("img2").getAttribute("src");document.getElementById("img2").src=document.getElementById("img3").getAttribute("src");document.getElementById("img3").src=img1src;document.getElementById("img1").style.animation="none";document.getElementById("img2").style.animation="none";document.getElementById("img3").style.animation="none";}})}</script></head><body><div style="position: relative; width: 700px;height: 500px;margin: 0 auto;" onclick="clicked();"><img id="img1" src="img/1.jpg" /><img id="img2" src="img/2.jpg" /><img id="img3" src="img/3.jpg"  /></div></body></html>

在谷歌浏览器上成功运行过


还有很多不足,希望高人指点。