js實現淡入淡出輪播圖
阿新 • • 發佈:2019-02-03
1.圖片淡入淡出自動輪播.
2.可以用按鈕控制輪播.
效果圖:
程式碼如下:
html+scc:
*{
margin: 0;
padding: 0;
}
html,body{
width: 100%;
}
.container{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50 %);
width: 800px;
height: 500px;
overflow: hidden;
}
.list img{
position: absolute;
left: 0;
top: 0;
width: 800px;
height: 500px;
opacity: 0;
z-index: 1;
transition: all 1s;
}
.list img:first-child{
opacity: 1;
z-index: 2;
}
.buttons{
position: absolute;
left: 50%;
bottom: 20px;
margin-left: -90px;
width: 180px;
text-align: center;
cursor: pointer;
z-index : 2;
}
.buttons span{
display: inline-block;
width: 20px;
height: 20px;
margin-right: 5px;
border-radius: 50%;
background: #aaa;
border: 1px solid #fff;
}
.buttons span:last-child{
margin-right: 0;
}
.buttons .on{
background: #000;
}
.arrow{
display: none;
position: absolute;
top: 230px;
width: 40px;
height: 40px;
background: rgba(0,0,0,0.4);
font-size: 40px;
font-weight: bold;
text-align: center;
cursor: pointer;
color: #fff;
z-index: 2;
}
.container:hover .arrow{
display: block;
}
#pre{
left: 0;
}
#next{
right: 0;
}
</style>
</head>
<body>
<div id="container" class="container">
<div id="list" class="list" >
<img src="i/8繡春刀.jpg" alt="繡春刀">
<img src="i/1當幸福來敲門.jpg" alt="當幸福來敲門">
<img src="i/2蝙蝠俠黑暗騎士.jpg" alt="蝙蝠俠黑暗騎士">
<img src="i/3後天.jpg" alt="後天">
<img src="i/7無間道.jpg" alt="無間道">
</div>
<div id="buttonGroup" class="buttons">
<span index="0" class="on"></span>
<span index="1"></span>
<span index="2"></span>
<span index="3"></span>
<span index="4"></span>
</div>
</div>
js:
function $(id) {
return document.getElementById(id);
}
var buttonGroup=$("buttonGroup"),
buttons=buttonGroup.getElementsByTagName('span'),
list=$("list"),
imgs=list.getElementsByTagName('img'),
flag=0,
container=$("container"),
timer;
function render(index){
for(var i=0;i<imgs.length;i++){
imgs[i].style.opacity="0";
imgs[i].style.zindex="1";
}
imgs[index].style.zindex="2";
imgs[index].style.opacity="1";
}
function bt_listen(event){
if (event.target&&event.target.tagName.toLowerCase()=='span') {
var index=event.target.getAttribute('index');
flag=index;
render(flag);
showButton();
}
}
function showButton(){
for(var i=0;i<buttons.length;i++){
buttons[i].className=buttons[i].className.replace(/\s*on/,"");
}
buttons[flag].className+=" on";
}
function play(){
timer=setInterval(function(){
if (flag==4) {
flag=0;
}else{
flag++;
}
render(flag);
showButton();
},3000);
}
function stop(){
clearInterval(timer);
}
function start(){
buttonGroup.addEventListener('click',bt_listen,false);
container.addEventListener('mouseenter',stop,false);
container.addEventListener('mouseleave',play,false);
play();
}
start();
思路:
讓所有的圖片都position:absolute,顯示在一個容器內,設定除了第一張圖片之外的所有圖片opcity:0;將要顯示的圖片z-index設定為2,其他都設定為1.flag用來記錄當前的索引值。
render(index)將索引為index的圖片顯示.
showButton()通過flag值來渲染當前圖片對應的按鈕.
bt_listen()為按鈕的監聽函式,取出當前被點選按鈕的index屬性,然後用render()函式來渲染圖片,再呼叫showButton()渲染按鈕.
play()為自動輪播函式,設定setInterval,當flag=4時,重置為0,否則flag++,然後呼叫render和showButton.