轮播图通常是关注的焦点,用于照片画廊或许多当代网站的大中心舞台。虽然过去Adobe Flash经常是使用CSS3和JavaScript的首选工具,但是轮播图可以轻松实现而无需大量代码。
我在这里使用的技术是使用标准JavaScript和CSS3实现简单轮播图的最简单方法之一,具有良好的交叉渐变过渡效果。
基本HTML是微不足道的。只需将几个图像放入div容器中:
使用CSS在容器内堆叠所有图片并定义过渡(特定于浏览器的前缀可能必须用于过渡):/* the slide container with a fixed size */
.slides {
box-shadow: 0px 0px 6px black;
margin: 0 auto;
width: 500px;
height: 300px;
position: relative;
}
/* the images are positioned absolutely to stack. opacity transitions are animated. */
.slides img {
display: block;
position: absolute;
transition: opacity 1s;
opacity: 0;
width: 100%;
}
/* the first image is the current slide. it's faded in. */
.slides img:first-child {
z-index: 2;
/* frontmost */
opacity: 1;
}
/* the last image is the previous slide. it's behind the current slide and it's faded over. */
.slides img:last-child {
z-index: 1;
/* behind current slide */
opacity: 1;
}
在这个简单的设置之后,剩下的就是更改轮播图的顺序以推进轮播图放映。以下代码段定期将第一张图像(当前图片)移动到容器的末尾,从而使下一张图像成为当前图片。由于上面定义的CSS规则,更改以交叉渐变为动画。function nextSlide() {
var q = function(sel) {
return document.querySelector(sel);
}
q(".slides").appendChild(q(".slides img:first-child"));
}
setInterval(nextSlide, 3000)
以上就是步骤的分析,下面是完整代码
function nextSlide() {
if (typeof $ == "undefined") var $ = function(sel) { return document.querySelector(sel); }
$(".slides").appendChild($(".slides img:first-child"));
}
setInterval(nextSlide, 3000)
img{
width: 500px;
height: 300px;
}
.slides {
box-shadow: 0px 0px 6px black;
margin: 0 auto;
width: 500px;
height: 300px;
overflow: hidden;
}
.slides img {
position: absolute;
transition: opacity 1s;
opacity: 0;
}
.slides img:first-child {
z-index: 2;
opacity: 1;
}
.slides img:last-child {
z-index: 1;
opacity: 1;
}
效果如下: