jQuery:缩放时使用scrollLeft不准确

时间:2016-06-16 15:00:42

标签: javascript jquery

我有一个带有链接和缩略图的可滚动容器 - scrollLeft到缩略图,具体取决于点击的链接,通常正常工作。

但是,当我使用transform缩放主容器时,scrollLeft会滚动到错误的位置。

有任何想法如何解决这个问题?

scroll: function(){
  var chapterName = this.chapter.getAttribute('data-chapter');
  var thumbnail = $('.thumbnail-content[data-chapter="'+chapterName+'"]').parent();
  if ( !$(this.chapter).hasClass('active-chapter') ){
    $('.active-chapter').removeClass('active-chapter');
    $('#thumbnail-container').animate({
      'scrollLeft' : '+='+thumbnail.position().left
    },{
      duration : 400,
      easing : 'easeOutSine'
    });
    $(this.chapter).addClass('active-chapter');
  }
}

reScale: function() {
  var windowHeight = $(window).height() - 20;
  if (windowHeight <= 827) {
    $('#viewer-container').addClass('scale scale075');
  }
}

CSS:

.scale075 {
  -webkit-transform: scale(0.75);  /* Chrome, Safari 3.1+ */
  -webkit-transform-origin: 50% 50%;
  -moz-transform: scale(0.75);  /* Firefox 3.5+ */
  -moz-transform-origin: 50% 50%;
  -ms-transform: scale(0.75);  /* IE 9 */
  -ms-transform-origin: 50% 50%;
  -o-transform: scale(0.75);  /* Opera 10.50-12.00 */
  -o-transform-origin: 50% 50%;
  transform: scale(0.75);  /* Firefox 16+, IE 10+, Opera 12.10+ */
  transform-origin: 50% 50%;
}

Here is a fiddle

2 个答案:

答案 0 :(得分:2)

$('#thumbnail-container').animate({
        'scrollLeft' : thumbnail[0].offsetLeft/*change here*/
      },{
        duration : 400,
        easing : 'easeOutSine'
      });

我认为,在这张票中,使用绝对位置然后相对位置会更好。 然后offsetLeft与变换无关,所以一切正常。

fiddle

答案 1 :(得分:1)

如果您知道脚本中的比例,则可以解决此问题。 我修改了你的小提琴来修复它并尝试修复你的示例代码。

Here is a fiddle

因此当您转换为0.75时,将变量设置为0.75,然后在设置scrollLeft时,将缩略图位置乘以1 / scale

var scrollScale = 1;

...

scroll: function(){
  var chapterName = this.chapter.getAttribute('data-chapter');
  var thumbnail = $('.thumbnail-content[data-chapter="'+chapterName+'"]').parent();
  if ( !$(this.chapter).hasClass('active-chapter') ){
    $('.active-chapter').removeClass('active-chapter');
    $('#thumbnail-container').animate({
      'scrollLeft' : '+='+thumbnail.position().left * (1/scrollScale)
    },{
      duration : 400,
      easing : 'easeOutSine'
    });
    $(this.chapter).addClass('active-chapter');
  }
}

reScale: function() {
  var windowHeight = $(window).height() - 20;
  scrollScale = 1;
  if (windowHeight <= 827) {
    $('#viewer-container').addClass('scale scale075');
    scrollScale = 0.75;
  }
}

希望能解决您的问题,或者让您了解如何更加动态地解决问题。

所以原因是position()。left在重新计算位置时会使用你的变换。但是scrollLeft不检查变换。所以你重新计算位置,使它们使用相同的比例。