Цель — отображать документы в формате A4, каждый из которых содержит предварительный просмотр Содержимое HTML, извлеченное из файла JSON, полученного через API.
Пример полученной структуры HTML:
Some text here1
Some text here2
Some text here3
Other text here1
Other text here2
Other text here3
Я загрузил изображение, чтобы предоставить больше контекста.

Основная проблема, с которой я сталкиваюсь, возникает, когда текст в одном из блоков HTML превышает максимальную высоту контейнера (.content), как указано в текущем дисплей с синей рамкой. В настоящее время я решаю эту проблему, управляя переносом узла с одной страницы на другую.
Мой стартовый подход предполагает перебор узлов с помощью класса .paragraph-wrapper. Когда один из этих узлов достигает максимальной высоты, я добавляю его на новую динамически создаваемую страницу .a4. Однако, перебирая узлы целиком, я теряю точность позиционирования текста внутри нового блока, особенно если текстовых/дочерних узлов внутри родительского узла много.
Итак, , я ищу способ разделить узел контейнера, например .paragraph-wrapper, на два отдельных узла, если один из его дочерних элементов превышает нижнюю границу контейнера .content. Каждый новый узел должен сохранять те же родительские элементы div, что и исходный узел, и связанные с ним встроенные стили.
Пример того, чего я хотел бы достичь, начиная с предыдущего кода:
Some text here1
Some text here2
Some text here3
Other text here1
Other text here2
***Here finish the first A4 page***
***Here start the second A4 page***
Other text here3
Часть моего текущего кода:
const content = document.querySelectorAll('.content');
const a4HeightWithoutPadding = evaluateContentHeight();
const lastContent = content[content.length - 1];
staticNodeArray.forEach(node => {
// Append node to last content element
lastContent.appendChild(node);
node.className = 'paragraph-wrapper';
const nodeOffsetBottom = node.offsetTop + node.offsetHeight;
// If the parent node reaches the bottom side of .content, make a new A4 page
if (nodeOffsetBottom > a4HeightWithoutPadding) {
// Increment contentId for new page
contentId += 1;
// Create a new A4
const newPage = createNewPage(fileId, contentId);
// Append the A4 to the container
container.appendChild(newPage);
// Moving the overflowed content to the new A4
const newContent = newPage.querySelector('.content');
newContent.appendChild(node);
}
});
// Create a new A4 page
function createNewPage(fileId, contentId) {
const newA4Page = document.createElement('div');
newA4Page.className = 'a4';
newA4Page.setAttribute('style', 'padding: 20px');
newA4Page.setAttribute('size', 'A4');
newA4Page.setAttribute('contenteditable', 'true');
newA4Page.setAttribute('fileId', fileId);
newA4Page.innerHTML = ``;
return newA4Page
}
function evaluateContentHeight() {
const a4NodeList = document.querySelectorAll('.a4');
// The last A4 created
const a4 = a4NodeList[a4NodeList.length - 1];
// Calculate the A4 height
const a4Height = a4.clientHeight;
// Calculate the value of top and bottom padding
const style = window.getComputedStyle(a4);
const paddingTop = parseFloat(style.paddingTop);
const paddingBottom = parseFloat(style.paddingBottom);
// Calculate the final value of A4 height without the padding of the A4
const a4HeightWithoutPadding = a4Height - paddingTop - paddingBottom;
return a4HeightWithoutPadding
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... nother-div
Мобильная версия