js实现幻灯片轮播图

2022-01-11,,

这篇文章主要为大家详细介绍了js实现幻灯片轮播图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了js实现幻灯片轮播图的具体代码,供大家参考,具体内容如下

1.html

选取了五张图片 放入div中,然后是左右箭头,以及按钮,代码如下

   轮播图   
  • 1
  • 2
  • 3
  • 4
  • 5

2.css给div设置居中

将所有图片隐藏,设置箭头和小圆点的样式
代码如下

 *{ margin:0; padding:0; text-decoration: none; list-style: none; } #box{ width:800px; height: 500px; margin:50px auto 0px; position: relative; } #box img{ width:800px; height: 500px; display: none; animation:fade 3s; } #box .arrow{ width:800px; height: 80px; position: absolute; top:50%; margin-top: -40px; } #box .arrow .left,.right{ display: inline-block; line-height: 80px; width: 50px; height:80px; } #box .arrow .left:hover{ background:rgba(0,0,0,0.8); } #box .arrow .right:hover{ background:rgba(0,0,0,0.8); } #box .arrow .right{ text-align: right; position: absolute; right:0; } #box .arrow a{ font-size: 50px; color: #ffffff; } #box .btn{ position: absolute; bottom: 10px; left:50%; margin-left: -98.47px; text-align: center; } #box .btn li{ text-align: center; margin:0 5px; padding: 10px; float:left; background:white; border-radius:20%; cursor: pointer; transition: background 2s ease; } #box .btn .on{ background: #000; color:white; } @keyframes fade{ from{ opacity:.4; } to{ opacity:1; } }

3.js部分

js设定让当前图片显示display:block,其他图片隐藏display:none;

js代码如下

 window.onload=function () { var left=document.getElementsByClassName("left")[0]; var right=document.getElementsByClassName("right")[0]; var btn=document.getElementsByClassName("btn")[0].getElementsByTagName("li"); var box=document.getElementById("box"); var slideIndex=1; var index=1; var timer; //图片切换函数 showSlides(slideIndex); function showSlides(n) { var slides=document.getElementById("box").getElementsByTagName("img"); for(var i=0;i1) { slideIndex--; showSlides(slideIndex); }else { slideIndex=5; showSlides(slideIndex); } } right.onclick=function () { if(slideIndex<5) { slideIndex++; showSlides(slideIndex); }else { slideIndex=1; showSlides(slideIndex); } } //btn切换 for(var i=0;i<btn.length;i++){ btn[i].onclick=function () { var myslideIndex=this.getAttribute('slideIndex'); // var myindex=parseInt(this.getAttribute("index")); slideIndex=myslideIndex; showSlides(slideIndex); } } //自动播放 function play() { timer=setInterval(function () { right.onclick(); },4000); } function stop() { clearInterval(timer); } box.onmouseout=play; box.onmouseover=stop; play(); }

精彩专题分享:jQuery图片轮播JavaScript图片轮播Bootstrap图片轮播

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

以上就是js实现幻灯片轮播图的详细内容,更多请关注本站其它相关文章!

《js实现幻灯片轮播图.doc》

下载本文的Word格式文档,以方便收藏与打印。