2

我是一个 jQuery 新手,最近才开始。

我正在使用http://flesler.blogspot.com.au/2007/10/jqueryscrollto.html(Ariel Flesler 的 scrollTo 插件)

这是一个水平滚动的网站。

当窗口调整大小时,我试图滚动到最靠近窗口左侧的元素。

我似乎只能让它滚动到数组中的第一个元素,所以当我调整窗口大小时,无论窗口在哪里,窗口都会滚动到流中的第一个“.example”。

更新:我取得了一些进展,我添加了一个新变量来计算滚动的距离。现在我似乎需要一种方法来找出循环的最低值是在我的“if”语句中使用的,因为它似乎想从一个元素跳到下一个元素或根本没有。

"Uncaught TypeError: Cannot read property 'slice' of undefined是由于 scrollTo 的值为负数(您不能滚动到 0 以下,因为 0 是文档的开头)所以为了解决这个问题,我添加了到目前为止已滚动多少的值,然后添加了任何值element_position 必须正确计算。

更新 2:我的数学有问题,问题已更新以反映解决方案。现在唯一的问题是它是一个流畅的布局,所以在我的 if 语句中使用像“70”这样的固定值往往会在某个点之后破坏它。

jQuery

$(document).ready(function(){
   $(window).resize(function() {
      $('.example').each(function(index) {
          var example = $(this);
          var scroll_position = $('#container').scrollLeft();
      var element_position = example.offset().left;

          if (element_position < 70 && position > -70) {
              $('#container').scrollTo(scroll_position + element_position);
          }
      });
   });
});

HTML

<div id="container">
   <div class="example"></div>
   <div class="example"></div>
   <div class="example"></div>
   <div class="example"></div>
   <div class="example"></div>
   <div class="example"></div>
</div>

我还收到以下错误

"Uncaught TypeError: Cannot read property 'slice' of undefined 
4

1 回答 1

1

试试这个:

$(document).ready(function(){
   $(window).resize(function() {
      var scroll_position = $('#container').scrollLeft();
      $('.example').each(function() {
          var example = $(this);
          var left = example.offset().left;
          var right = left + example.width();

          if (right > 0) {
              $('#container').scrollTo(scroll_position + left);
              return false;
          }
      });
   });
});​

检查选定元素中第一个在视口中有右边框的元素。

于 2012-10-15T18:04:46.263 回答