私は非常に長い html ページを開発しており、デザインにはページのように垂直方向のコンテンツにブロックがあります。私がしたいのは、ユーザーの位置が正しい位置からわずかな距離内にある場合、ユーザーがページを下にスクロールして、各ページが画面の中央に正しく配置されるポイントに「スナップ」することです。
ページの他のものには jquery を使用しているので、関連するものがあれば喜んで使用します。
もちろん、アドバイスは大歓迎です。
私は非常に長い html ページを開発しており、デザインにはページのように垂直方向のコンテンツにブロックがあります。私がしたいのは、ユーザーの位置が正しい位置からわずかな距離内にある場合、ユーザーがページを下にスクロールして、各ページが画面の中央に正しく配置されるポイントに「スナップ」することです。
ページの他のものには jquery を使用しているので、関連するものがあれば喜んで使用します。
もちろん、アドバイスは大歓迎です。
これはテストされていませんが、動作するはずです。それがどのように機能するかの説明については、コメントを参照してください。
ポイントから離れてスクロールしようとしたときに繰り返しスナップされないように、ポイントがスナップされた後にポイントを無効にします。この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]);
}