Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Как создать пагинацию HTML страницы?

Василий Воробьёв Ученик (109), открыт 1 неделю назад
Предположим, что есть страница с очень длинным текстом и этот текст постоянно пополняется. Я хочу, что бы на странице отображалась только часть контента, а для просмотра остальных частей нужно было бы пролистывать страницы нажимая на цыфры.
Нужно что бы текст делился автоматически на определенные части даже когда контент будет пополнятся.
4 ответа
666 Мастер (2356) 1 неделю назад
To create pagination for an HTML page, you can use a combination of HTML, CSS, and JavaScript. Here's a basic example of how you can achieve this:

HTML:
```html
<div id="content">
<!-- your long text content here -->
</div>

<div id="pagination">
<ul>
<li><a href="#1">1</a></li>
<li><a href="#2">2</a></li>
<li><a href="#3">3</a></li>
<!-- add more links as needed -->
</ul>
</div>
```
CSS:
```css
#content {
overflow: hidden;
height: 300px; /* adjust the height to fit your content */
padding: 20px;
}

#pagination {
text-align: center;
margin-top: 20px;
}

#pagination ul {
list-style: none;
margin: 0;
padding: 0;
}

#pagination li {
display: inline-block;
margin-right: 10px;
}

#pagination a {
text-decoration: none;
color: #337ab7;
}

#pagination a:hover {
color: #23527c;
}
```
JavaScript:
```javascript
const content = document.getElementById('content');
const pagination = document.getElementById('pagination');
const links = document.querySelectorAll('#pagination li a');

let currentPage = 1;
let totalPages = 0;

// calculate the total number of pages
totalPages = Math.ceil(content.textContent.length / 200); // adjust the number to fit your content

// add event listeners to the links
links.forEach((link) => {
link.addEventListener('click', (e) => {
e.preventDefault();
const page = parseInt(link.textContent);
currentPage = page;
updateContent();
});
});

// update the content and pagination links
function updateContent() {
const start = (currentPage - 1) * 200; // adjust the number to fit your content
const end = start + 200;
const contentText = content.textContent.substring(start, end);
content.innerHTML = contentText;

// update the pagination links
links.forEach((link) => {
link.classList.remove('active');
});
links[currentPage - 1].classList.add('active');
}
```
This code assumes that you have a `#content` div that contains the long text content, and a `#pagination` div that contains the pagination links. The JavaScript code calculates the total number of pages based on the length of the content text, and adds event listeners to the pagination links. When a link is clicked, the `updateContent` function is called, which updates the content and pagination links accordingly.

You can adjust the CSS and JavaScript code to fit your specific needs, such as changing the layout, adding more features, or improving the performance.
Василий ВоробьёвУченик (109) 1 неделю назад
Спасибо. А если в качестве контента у меня не просто текст, а различные блоки (картинки, текст, списки, таблицы) со своими стилями. Как в этом случаи разбить контент?
www www Искусственный Интеллект (125186) 1 неделю назад
Проще всего это сделать на уровне сервера. Выдавать части данных по запросу + разместить ссылки на остальные части (стрелочками, цифрами, как удобнее)
Gerdot Lareston Мыслитель (8727) 1 неделю назад
  




Pagination Example








 /* styles.css */ 
#content {
max-width: 800px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
}

#pagination {
text-align: center;
margin-top: 20px;
}

.pagination-button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ccc;
cursor: pointer;
}

.pagination-button.active {
background-color: #007bff;
color: white;
border-color: #007bff;
}

.pagination-button:hover {
background-color: #0056b3;
color: white;
}
 // script.js 

document.addEventListener("DOMContentLoaded", function () {
const contentElement = document.getElementById('content');
const paginationElement = document.getElementById('pagination');
const itemsPerPage = 5; // Количество элементов на странице
let currentPage = 1;

// Пример длинного текста
const text = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla condimentum tortor sem, in semper nisl bibendum eu.
Nunc non varius justo, et facilisis arcu. Quisque ac vulputate velit. Suspendisse molestie congue odio.
Proin pharetra viverra mauris, nec fermentum felis blandit vel. Aliquam nec ipsum eget elit gravida rutrum.
Ut vel mauris volutpat, placerat erat ut, imperdiet eros. Duis at facilisis sem, nec elementum sapien.
... (повторить для получения большого текста) ...
`;

const paragraphs = text.split('\n').filter(p => p.trim() !== '');

function renderContent() {
contentElement.innerHTML = '';
const start = (currentPage - 1) * itemsPerPage;
const end = start + itemsPerPage;
const pageItems = paragraphs.slice(start, end);

pageItems.forEach(item => {
const p = document.createElement('p');
p.textContent = item;
contentElement.appendChild(p);
});

renderPagination();
}

function renderPagination() {
paginationElement.innerHTML = '';
const totalPages = Math.ceil(paragraphs.length / itemsPerPage);

for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.textContent = i;
button.classList.add('pagination-button');
if (i === currentPage) {
button.classList.add('active');
}
button.addEventListener('click', () => {
currentPage = i;
renderContent();
});
paginationElement.appendChild(button);
}
}

renderContent();
});
Ааабаев Аааб Мыслитель (9094) 1 неделю назад
это не пагинация, дружок... пагинация - это перебор страниц... ты же задумал рвать 1 (ОДНУ) страницу на куски...
Василий ВоробьёвУченик (109) 1 неделю назад
Не може быдь! А шо ето?
Ааабаев Аааб Мыслитель (9094) Василий Воробьёв, а шо - по-китайски ж..опа! вот ты в нее и попал! дошокался.
Похожие вопросы