HTML DOM-->轮播图
实现:图片的轮播
html代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>轮播图</title> <!-- 导入css样式--> <link rel="stylesheet" type='text/css' href="css/new_file.css"> </head> <body> <div id="box"> <!-- 轮播图片--> <img src="./img/01.jpg" id="pic"> <!-- 轮播数字原点--> <ul id="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> </ul> <!-- 左边--> <div id="left" class="bt"> < </div> <!-- 右边--> <div id="right" class="bt"> > </div> </div> </body> <!-- 导入js--> <script type="text/javascript" src="./js/new_file.js"></script> </html>
css代码:
*{ padding: 0; margin: 0; } #pic{ width: 790px; height: 340px; } #box{ width: 790px; height: 340px; margin:0 auto; position: relative; } .bt{ width: 50px; height: 80px; background-color: rgba(0,0,0,0.2); color: #fff; font-size: 30px; line-height: 80px; text-align: center; position: absolute; top: 100px; display: none; } #left{ left: 0; } #right{ right: 0; } #list{ list-style: none; position: absolute; bottom: 20px; left:250px; } #list li{ float: left; width: 20px; height: 20px; background-color: #aaa; margin-left: 10px; border-radius: 50%; text-align: center; line-height: 20px; }
js代码:
var jsBOX = document.getElementById('box') var jsPic = document.getElementById('pic') var jsLeft = document.getElementById('left') var jsRight = document.getElementById('right') var jsListArr = document.getElementsByTagName('li') //第一个li设置为红色 jsListArr[0].style.backgroundColor = 'red' //启动一个定时器区更换jsPic中的src属性 var currentPage = 0 var timer = window.setInterval(startLoop,1000) //启动轮播函数 function startLoop(){ currentPage++ changePage() } //换页函数 function changePage(){ if(currentPage == 9){ currentPage = 1 }else if(currentPage==0){ currentPage=8 } jsPic.src = './img/0'+currentPage+'.jpg' //清空所有小圆点的颜色 for(var i=0;i<jsListArr.length;i++){ jsListArr[i].style.backgroundColor='#aaa' } //给小圆点添加颜色 jsListArr[currentPage-1].style.backgroundColor='red' } //鼠标进入BOX:停止计时器 jsBOX.addEventListener('mouseover',overfunc,false) function overfunc(){ clearInterval(timer) jsLeft.style.display = 'block' jsRight.style.display = 'block' } //鼠标移出BOX:重启计时器 jsBOX.addEventListener('mouseout',outfunc,false) function outfunc(){ timer = setInterval(startLoop,1000) jsLeft.style.display = 'none' jsRight.style.display = 'none' } //鼠标进入左右盒子 jsLeft.addEventListener('mouseover',deep,false) jsRight.addEventListener('mouseover',deep,false) //颜色加深 function deep(){ this.style.backgroundColor = 'rgba(0,0,0,0.6)' } //鼠标移出左右盒子 jsLeft.addEventListener('mouseout',nodeep,false) jsRight.addEventListener('mouseout',nodeep,false) //颜色变浅 function nodeep(){ this.style.backgroundColor = 'rgba(0,0,0,0.2)' } //点击左侧换页 jsRight.addEventListener('click',startLoop,false) //点击右侧换页 jsLeft.addEventListener('click',function(){ currentPage-- changePage() },false) //进入小圆点 for(var i = 0;i<jsListArr.length;i++){ jsListArr[i].addEventListener('mouseover',function(){ currentPage = parseInt(this.innerHTML) changePage() },false) }
输出效果:
心揣信念,梦想就在脚下!