javascript – 设置拇指条右箭头限制的最佳方法?

这是我的sideThumb函数和注释. this.panos是拇指的数量,this.translateX是拇指移动的像素数.

slideThumbs (direction) { // slide to left or right
  const thumbWidth = 160 + 6 // plus padding
  const visibleThumbsWidth = thumbWidth * 5 // slide 5 thumbs at a time

  // exclude last thumb
  const totalThumbsWidth = thumbWidth * (this.panos.length - 1)
  if (direction === 'left' && this.translateX !== 0) {
    this.translateX += visibleThumbsWidth
  }
  if (direction === 'right' && this.translateX !== -totalThumbsWidth) {
    this.translateX -= visibleThumbsWidth
  }
}

最终结果:

transform: translate(-830px, 0px); // clicking the right arrow one time
transform: translate(-1660px, 0px); // and two times

设置左箭头的限制很容易:如果this.translateX为0,请不要让函数运行.设置右箭头的限制更加困难.使用-totalThumbsWidth是不可靠的,因为具有11和14个panos应该带来相同的结果(使用户能够按向右箭头2次).

《javascript – 设置拇指条右箭头限制的最佳方法?》

解决这个问题的最佳方法是什么?

编辑:

我做的一些数学:

 6 thumbs => can click right arrow 1 time
 11 thumbs => can click right arrow 2 times
 16 thumbs => can click right arrow 3 times

 5 * x + 1 = 16 // this is how I get x in the third example
 x = (this.panos.length - 1) / 5 // what to do with this?

我确信我可以在数学计算中使用它.

最佳答案 你可以尝试这样的东西,但没有小提琴,我无法验证它是否适用于你的特定情况

slideThumbs (direction) { // slide to left or right
  const thumbWidth = 160 + 6 // plus padding
  const currentTilePosition = (this.translateX / thumbWidth) + 5; // get the current number for the last visible tile / we +5 because translateX starts at 0
  const tilesToGo = (this.panos.length - currentTilePosition) - 1; // how many tiles to go?

  var incrementThumbs = thumbWidth * 5 // slide 5 thumbs at a time

  if (direction === 'right' && tilesToGo < 5) {
      if (tilesToGo === 0) {
       incrementThumbs = 0;
      } else if {
       incrementThumbs = thumbWidth * tilesToGo; 
      }
  }

  if (direction === 'left' && currentTilesPosition % 5 !== 0) {
     incrementThumbs = thumbWidth * (currentTilesPosition % 5);
  }

  if (direction === 'left' && this.translateX !== 0) {
    this.translateX += incrementThumbs
  }
  if (direction === 'right') {
    this.translateX -= incrementThumbs
  }
}

这样做也将确保最后的瓷砖总是与屏幕的右侧齐平,如果瓷砖的总数不是5的倍数,我还添加了一些代码以便于从这种情况向左移动, 希望能帮助到你

点赞