简体   繁体   English

div滑块超出边界(数组长度)

[英]div slider goes beyond the borders(array length)

my div slider ignores the borders that i've made, can't find the mistakes. 我的div滑块忽略了我所做的边框,找不到错误。 PS right/left functions are called in tag attribute onclick:'slider.right()'. PS右/左函数在标记属性onclick:'slider.right()'中调用。 I'm just learning, I know that the elegance of the code is far from being ideal. 我只是在学习,我知道代码的优雅远非理想。

    let elArr = [];

let pusher = elArr.push(document.querySelectorAll('#scr>div'));
let elements = Array.from(elArr[0]);
let slider = {
  frame: 0,
  set: function(element){
    var container = document.getElementById('scr');
    container = element.style.visibility='visible';
  },

  init: function(){
    this.set(elements[this.frame]);
  },

  left: function(){
    elements[this.frame].style.visibility='hidden';
    this.frame--;
    if(this.frame<0)
    this.frame = elements.length - 1;
    this.set(elements[this.frame]);
  },

  right: function(){
    elements[this.frame].style.visibility='hidden';
    this.frame++;
    if(this.frame>elements.length)
    this.frame = 0;
    this.set(elements[this.frame]);
  }

};

window.onload = function(){
  slider.init();
}

One great guy just helped me, so there is an incorrect condition 一个好人刚刚帮了我,所以情况不对

if(this.frame>elements.length)

it drops 'frame' value, when current value is bigger then the number of elements in the array, but taking in consideration the fact, that indexation of the elements starts with 0, when frame is equal to elements.length - value becomes undefined, so frame value doesn't drop. 当当前值大于数组中元素的数量时,它将丢弃“帧”值,但考虑到事实,当帧等于elements时,元素的索引从0开始。length-value变为不确定,因此帧值不会下降。

So, we need to change condition to a comparison == or to make it >=; 因此,我们需要将条件更改为比较==或使其> =; thnx to user:186999 for the decision 致用户:186999

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM