0

我正在开发一个很长的 html 页面,并且该设计在垂直的内容上像页面一样有块。我想要做的是当用户向下滚动页面以“捕捉”到一个点时,如果用户的位置在正确位置的一小段距离内,则每个页面都正确放置在屏幕中心。

我们将 jquery 用于页面上的其他内容,如果它有相关内容,我们很乐意使用它。

任何建议当然都非常感谢。

4

1 回答 1

0

没有对此进行测试,但它应该可以工作。有关其工作原理的说明,请参阅注释。

我在它被捕捉后禁用该点,以便在尝试滚动远离它时不会重复捕捉它。该leniancy变量既是距用户在再次激活之前必须滚动的点的距离,也是捕捉点之前的距离。

var points = [250, 675, 1225, $("#someDiv")]; // y coordinates or jQuery objects you want to centre against.
var disabledPoints = []; // Points that you won't snap to (leave empty) this allows user to scroll from a point
var wMid = ($(window).height() / 2); // Pixels to centre of window
var leniancy = 100; // Number of pixels ether side of a point before it is snapped

$.each(points, function(key, value) { // Loop through points
   if (value instanceof jQuery) { // If value is a jQuery object
      function setObjectPos(){
         var offset = value.offset();
         var centerPoint = offset.top + (value.height() /2); // Calculate object centre relative to document
         value.data('centerPoint', centerPoint); // Store it for later
      });
      value.bind('DOMSubtreeModified', setObjectPos); // If div changes update  center position.
   }
}

$(window).resize(function () {  // If user resizes window update window mid-point variable
   wMid = ($(window).height() / 2);
});

$(window).scroll(function () { 
   var centerPos = $(window).scrollTop() + wMid; // Position of screen center relative to document
   $.each(points, function(key, value) { // Loop through points
      if (value instanceof jQuery) {
         value = value.data('centerPoint');
      }
      var offset = value - centerPos;
      if(checkDistance(offset, leniancy)) {
         snapToPoint(key); // Success! snap that point
         return false; // Kill the loop
      }
   });
   $.each(disabledPoints, function(key, value) { // Loop through disabled points
      if (value instanceof jQuery) {
         value = value.data('centerPoint');
      }
      var offset = value - centerPos;
      if(!checkDistance(offset, leniancy)) {
         enablePoint(key); // Success! enable that point
      }
   });
});

function checkDistance(offset, margin) {
   if (offset > 0) { 
      if (offset <= margin) { 
         return true;
      }
   } else {
      if (offset >= (margin * -1)) {
         return true;
      }
   }
   return false;
}

function snapToPoint(index) {
   var offset = (points[index] instanceof jQuery) ? points[index].data('centerPoint') - wMid : points[index] - wMid;
   $(window).scrollTop(offset); 
   var point = points.splice(index, 1); 
   disabledPoints.push(point[0]); 
}

function enablePoint(index) {
   var point = disabledPoints.splice(index, 1);
   points.push(point[0]); 
}​
于 2012-10-24T08:32:59.043 回答