我正在开发一个很长的html页面,并且该设计在页面上垂直打印内容。我想要做的是当用户向下滚动页面以“捕捉”到每个页面正确放置在屏幕中心的点时,如果用户的位置在正确位置的一小段距离内。
我们正在使用jquery来处理页面上的其他内容,如果它有相关内容,我们很乐意使用它。
任何建议当然都非常感谢。
答案 0 :(得分: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]);
}