6.轮播.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var imgBox = document.querySelectorAll("img");
  2. var points = document.querySelectorAll("#list li");
  3. var prev = document.querySelector(".prev");
  4. var next = document.querySelector(".next");
  5. var container = document.getElementById("container");
  6. var currentIndex = 0;
  7. // 封装切换方法
  8. function autoPlay(ind) {
  9. // 清空所有样式
  10. for(var i=0;i<points.length;i++) {
  11. imgBox[i].className = "choose";
  12. points[i].className = "";
  13. }
  14. // 添加点击下标的样式
  15. imgBox[ind].className = "choose active";
  16. points[ind].className = "selected";
  17. }
  18. // 点击按钮切换图片
  19. for(var i=0;i<points.length;i++) {
  20. points[i].index = i;
  21. points[i].onclick = function() {
  22. console.log("点击")
  23. currentIndex = this.index;
  24. autoPlay(currentIndex);
  25. }
  26. }
  27. // 上一页
  28. prev.onclick = function() {
  29. currentIndex--;
  30. if(currentIndex < 0) {
  31. currentIndex = imgBox.length - 1;
  32. }
  33. autoPlay(currentIndex);
  34. }
  35. // 下一页
  36. next.onclick = function() {
  37. currentIndex++;
  38. if(currentIndex == imgBox.length) {
  39. currentIndex = 0;
  40. }
  41. autoPlay(currentIndex);
  42. }
  43. // 自动轮播
  44. var timer = setInterval(function() {
  45. next.onclick();
  46. },1000)
  47. // 鼠标划入事件
  48. container.onmousemove = function() {
  49. prev.style.display = 'block';
  50. next.style.display = 'block';
  51. clearInterval(timer)
  52. }
  53. // 鼠标划出事件
  54. container.onmouseout = function() {
  55. prev.style.display = 'none';
  56. next.style.display = 'none';
  57. timer = setInterval(function() {
  58. next.onclick();
  59. },1000)
  60. }