Как программно обрабатывать поведение пролистывания и прокрутки?Html

Программисты Html
Ответить
Anonymous
 Как программно обрабатывать поведение пролистывания и прокрутки?

Сообщение Anonymous »

Я заметил, что шаблон, над которым я сейчас работаю, имеет проблему с вертикальной прокруткой при тестировании на планшетах и/или мобильных устройствах.
Вот текущее поведение:
Изображение

Примечания. Имеются проблемы с поведением прокрутки. Прокрутка колесика мыши работает правильно, но прокрутка с помощью прокрутки не работает должным образом.
Вот ссылка, которую я не могу воспроизвести в своем шаблоне:
Изображение

Примечания. Это имеет почти ту же структуру кода, что и шаблон с проблема.

Вот соответствующие фрагменты кода:

Код: Выделить всё

[list]
[*][url=#tip-answer-1-11]Consejo # 1/11[/url]
[*][url=#tip-answer-2-11]Consejo # 2/11[/url]
[*][url=#tip-answer-3-11]Consejo # 3/11[/url]
[*][url=#tip-answer-4-11]Consejo # 4/11[/url]
[*][url=#tip-answer-5-11]Consejo # 5/11[/url]
[*][url=#tip-answer-6-11]Consejo # 6/11[/url]
[*][url=#tip-answer-7-11]Consejo # 7/11[/url]
[*][url=#tip-answer-8-11]Consejo # 8/11[/url]
[*][url=#tip-answer-9-11]Consejo # 9/11[/url]
[*][url=#tip-answer-10-11]Consejo # 10/11[/url]
[*][url=#tip-answer-11-11]Consejo # 11/11[/url]
[/list]

Код: Выделить всё

/**
* Place the box inside the container with the class .zld-scrollbar-custom.
* The child box should have an auto height, but .zld-scrollbar-custom should have a defined height.
*/
function ZLDCustomScrollbarsInit() {
$(".zld-scrollbar-custom").each(function (index_scrollbar) {
const scroll_thumb_id = `scroll-thumb-${index_scrollbar}`;
const inner_box = $(this).find(">*").first();
// Both container and inner_box refer to the same element: the first box inside .zld-scrollbar-custom that will scroll.
const container = inner_box;
const zldScrollPanel = $(this);

if (zldScrollPanel.attr("data-initilized") !== "Y") {
// Add the classes of the child box to its parent.
zldScrollPanel.attr("class", `${zldScrollPanel.attr("class")} ${inner_box.attr("class")}`);
inner_box.addClass("scrollable-content");

zldScrollPanel.attr("data-initilized", "Y");
zldScrollPanel.append(`



`);

window[`point-${scroll_thumb_id}`] = { x: 0, y: 0 };

/**
* Using the plugin for dragging (https://interactjs.io/)
*/
interact(`#${scroll_thumb_id}`).draggable({
listeners: {
start(event) {
$("body").addClass("noselect");
$(event.target).addClass("dragged");
},
end(event) {
$("body").removeClass("noselect");
$(event.target).removeClass("dragged");
},
move(event) {
move(event.target, event.dx, event.dy);
},
},
});

/**
* Container is the content box that should have scrollbars.
*/
container.on("mousewheel DOMMouseScroll", function (e) {
// If the parent of the container has the class .not-scrollable, enable standard scrolling.
if (container.parent().is(".not-scrollable")) {
return true;
}

const deltaMovingY = getMaxScrollY() > 200 ? 10 : 100;
const delta =
e.originalEvent.detail !== undefined && e.originalEvent.detail !== 0
? e.originalEvent.detail * -1 // Firefox
: e.originalEvent.wheelDelta; // Chrome

if (delta / 120 >  0) {
move($(`#${scroll_thumb_id}`)[0], 0, 0 - deltaMovingY);
} else {
move($(`#${scroll_thumb_id}`)[0], 0, deltaMovingY);
}

// Prevent window scrolling when hovering over this element.
return false;
});

// Touch event handling
let touchStartY = 0;

container.on("touchstart", function (e) {
touchStartY = e.originalEvent.touches[0].clientY;
});

container.on("touchmove", function (e) {
if (container.parent().is(".not-scrollable")) {
return true;
}

const touchEndY = e.originalEvent.touches[0].clientY;
const deltaMovingY = getMaxScrollY() > 200 ? 10 : 100;
const deltaY = touchStartY - touchEndY; // Determine swipe direction

if (deltaY > 0) {
move($(`#${scroll_thumb_id}`)[0], 0, deltaMovingY); // Scroll down
} else {
move($(`#${scroll_thumb_id}`)[0], 0, -deltaMovingY); // Scroll up
}

touchStartY = touchEndY; // Update for smooth scrolling

e.preventDefault(); // Prevent default scrolling
});
}

const move = function (element, dx, dy) {
const thumb = $(element);
const parentThumb = thumb.parent();
const zldScrollBarPanel = parentThumb.closest(".zld-scrollbar-custom");
const position = window[`point-${scroll_thumb_id}`];
position.y += dy;

if (position.y < 0) {
position.y = 0;
} else if (position.y + thumb.height() > parentThumb.height()) {
position.y = parentThumb.height() - thumb.height();
}

element.style.transform = `translate(${position.x}px, ${position.y}px)`;

const totalFreeSpace = parentThumb.height() - thumb.height();
// When the thumb is larger than the parent, scrolling is not needed.
if (totalFreeSpace  {
const parentThumb = $(thumb).parent();
const totalFreeSpace = parentThumb.height() - $(thumb).height();
const maxScroll = container[0].scrollHeight - container[0].clientHeight;

if (totalFreeSpace > 0 && maxScroll > 0) {
const percentScrolled = container.scrollTop() / maxScroll;
position.y = totalFreeSpace * percentScrolled;
}

thumb.style.transform = `translate(${position.x}px, ${position.y}px)`;
});
}

const setScrollbasSize = function () {
// Reset the scrollbar sizes (you can complete this if necessary).
};

// Resetting the scrollbar size.
setScrollbasSize();

// When initializing for the first time or resizing the browser, reset the positions.
if (1) {
move($(`#${scroll_thumb_id}`)[0], 0, 0);
}

// Check if the container contains enough content to enable scrolling.
if (container[0].scrollHeight > container[0].clientHeight) {
container.closest(".zld-scrollbar-custom").removeClass("not-scrollable");
} else {
container.closest(".zld-scrollbar-custom").addClass("not-scrollable");
}
});
}

$(window).on("resize", function () {
ZLDCustomScrollbarsInit();
});

$(window).on("orientationchange", function () {
ZLDCustomScrollbarsInit();
});

$(window).on("load", function () {
ZLDCustomScrollbarsInit();
});

$(document).ready(() => {
// Handle scrollbar initialization for elements that are hidden initially.
window.addEventListener(ON_TRANSITION_TO_SHOW_ENDED, () =>  {
ZLDCustomScrollbarsInit();
});
});
Я также пробовал применить прокрутку-поведение: плавно, но проблема не устранена.

Мне нужно не просто исправление кода, а руководство по тому, как справиться с таким поведением в целом. Я пытаюсь убедиться, что вертикальная прокрутка работает правильно на мобильных устройствах и планшетах, но не могу понять, что вызывает неправильное поведение прокрутки.

Подробнее здесь: https://stackoverflow.com/questions/798 ... l-behavior
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»