index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. window.onload = function () {
  2. var focus = document.querySelector('.focus');
  3. var arrow_l = document.querySelector('.arrow-l');
  4. var arrow_r = document.querySelector('.arrow-r');
  5. var ul = focus.querySelector('ul');
  6. var ol = focus.querySelector('.circle');
  7. focus.addEventListener('mouseenter', function () {
  8. arrow_l.style.display = 'block';
  9. arrow_r.style.display = 'block';
  10. clearInterval(timer);
  11. });
  12. focus.addEventListener('mouseleave', function () {
  13. arrow_l.style.display = 'none';
  14. arrow_r.style.display = 'none';
  15. timer = setInterval(() => {
  16. arrow_r.click();
  17. }, 2000);
  18. });
  19. for(var i = 0; i < ul.children.length; i++) {
  20. var li = this.document.createElement('li');
  21. li.setAttribute('index', i);
  22. ol.appendChild(li);
  23. li.addEventListener('click', function () {
  24. var index = this.getAttribute('index');
  25. var left = -1 * index * focus.offsetWidth;
  26. // 每点一个小li,就要滚动图片的位置
  27. animate(ul, left);
  28. liChange(this);
  29. num = index;
  30. });
  31. }
  32. ol.children[0].className = 'current';
  33. // 循环图片,克隆第一张放到尾部
  34. ul.appendChild(ul.children[0].cloneNode(true));
  35. var num = 0;
  36. arrow_l.addEventListener('click', function () {
  37. if(num == 0){
  38. num = ul.children.length-1;
  39. ul.style.left = -1 * num * focus.offsetWidth + 'px';
  40. }
  41. num--;
  42. var left = -1 * num * focus.offsetWidth;
  43. animate(ul, left);
  44. liChange(ol.children[num%ol.children.length]);
  45. });
  46. arrow_r.addEventListener('click', function () {
  47. if(num == ul.children.length-1){
  48. num = 0;
  49. ul.style.left = 0;
  50. }
  51. num++;
  52. var left = -1 * num * focus.offsetWidth;
  53. animate(ul, left);
  54. liChange(ol.children[num%ol.children.length]);
  55. });
  56. var timer = setInterval(() => {
  57. arrow_r.click();
  58. }, 2000);
  59. function liChange(obj) {
  60. // 排他思想,给点击的小li加上样式
  61. for(var i = 0; i < ol.children.length; i++){
  62. ol.children[i].className = '';
  63. }
  64. obj.className = 'current';
  65. }
  66. }