欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js 轮播效果实例分享

程序员文章站 2022-11-02 19:58:46
html

html

<!--图片轮播   start-->
<div class="pics-ul">
  <div class="pics-ulleft">              
    <ul id="allimg">
      <li><img src="img/img01.png"/></li>  
      <li><img src="img/img2.jpg"/></li>  
      <li><img src="img/img1.jpg"/></li>  
      <li><img src="img/img3.jpg"/></li>  
      <li><img src="img/img4.jpg"/></li>  
    </ul>
    <a name="btn" id="prev" class="prev" style="display: block;"></a>
    <a name="btn" id="next" class="next" style="display: block;"></a>
     <ul id="btn" class="pagination">
     <li class="hover"><a href="#0">1</a></li>
     <li><a href="#1">2</a></li>
     <li><a href="#2">3</a></li>
     <li><a href="#3">4</a></li>
     <li><a href="#4">5</a></li>
     </ul>
     </div>
     <div class="pics-ulright"><img src="img/imgright.png"/></div>
     </div>
<!--图片轮播   end-->  

js

/*图片轮播*/
var but1 = document.getelementbyid("prev");
var abtn = document.getelementbyid("btn").getelementsbytagname("li"); //获取所有的按钮
var lis = document.getelementbyid('allimg').getelementsbytagname('li');
var but2 = document.getelementbyid("next");
var index = 0;
var timer = null;
but2.onclick = function() {

  index++;
  if (index > lis.length - 1) {
    index = 0;
  }
  setimg(index);

}
but1.onclick = function() {
  index--;
  if (index < 0) {
    index = lis.length - 1;
  }
  setimg(index);

}
function changeimg() {
  if (index == lis.length - 1) { //当到最后一张图片时
    index = 0
  } else {
    index++; //图片索引发生改变
  }
  setimg(index);
}
function setimg(index) {
  for (j = 0; j < lis.length; j++) {
    lis[j].style.display = "none";
  }

  lis[index].style.display = "block";
  //按钮的样式要与图片对应
  for (var i = 0; i < abtn.length; i++) {
    abtn[i].classname = ""
  }
  abtn[index].classname = "hover";
}
//自动切换
timer = setinterval(changeimg, 3000);
//按钮
for (var i = 0; i < abtn.length; i++) {
  (function() {
    var p = i
    abtn[p].onclick = function() {
      index = p;
      setimg(index);
    }

  })();
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!