javascript实现幻灯片播放
实现原理
- step1 设置容器,包含图片、翻页、下标等元素,通过相对定位来布局。
- step2 将幻灯片变化,需要改变的元素放在一个字容器内,display设为none,并且采取动画来变化。
- step3设置js函数,将应该播放的元素样式激活,其他的元素仍为未激活状态或者不展示类的隐藏。
代码
html
Insert title here 1 / 3 文本 1 2 / 3 文本 2 3 / 3 文本 3 ❮ ❯
css
@charset "UTF-8";
* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;}
.mySlides {
display:none;
}
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
.dot {
cursor:pointer;
height: 13px;
width: 13px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
js
var slideIndex = 1;
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}//class为mySlides下的元素,即不展示项目的图片元素、数字元素和文本元素
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");//将激活的下标元素,改为不再展示
}
slides[slideIndex-1].style.display = "block";//轮播的元素展示
dots[slideIndex-1].className += " active";//轮播图片对应下标样式激活
}
showSlides(slideIndex);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



