设置拇指条右箭头限制的最佳方法是什么?

时间:2016-03-14 07:43:20

标签: javascript html css

这是我的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.translateX0,请不要让函数运行。设置右箭头的限制更加困难。使用-totalThumbsWidth不可靠,因为1114 panos应该带来相同的结果(让用户按下右箭头2次)。

enter image description here

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

修改

我做的一些数学:

 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?

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

2 个答案:

答案 0 :(得分:1)

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

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的倍数,我还添加了一些代码以方便向左移动这样的情况,希望有所帮助

答案 1 :(得分:0)

我终于设定了这样的限制:

  const thumbWidth = 166 // thumb width plus padding 160 + 6
  const visibleThumbsWidth = thumbWidth * 5

  const rightArrowClicks = (-this.translateX / thumbWidth) + 6
  console.log('TRANSLATE LENGTH', (-this.translateX / thumbWidth) + 6)
  console.log('PANO LENGTH', this.panos.length)
  if (direction === 'left' && this.translateX !== 0) {
    this.translateX += visibleThumbsWidth
  }
  if (direction === 'right' && rightArrowClicks <= this.panos.length) {
    this.translateX -= visibleThumbsWidth
  }

-this.translateX / thumbWidth是向左移动的拇指数。至于6 ...不确定为什么它适用于那个数字。我使用控制台日志来达到此解决方案。如果有人能向我解释我自己的代码,我会很高兴。