Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 10.01.2023, 18:23
Профессор
Отправить личное сообщение для ureech Посмотреть профиль Найти все сообщения от ureech
 
Регистрация: 11.03.2013
Сообщений: 765

Пагинация страниц
Привет. Застрял на этом деле. Не могу сообразить логику. Открываю страницу. На ней текст. Нужно что бы и скролился вниз и "листался"(пока кнопки) в любой момент. Начал с подсчёта строк. Но все строки не знаю как посчитать. Скорее всего никак. Только в окне. Как это применить не понятно. Стал считать теги <p>. Их можно посчитать все. Но куда думать дальше никак... Подскажите, кто знает. Всё на стороне клиента. С сервера только файл с тестом.
Ответить с цитированием
  #2 (permalink)  
Старый 10.01.2023, 18:49
Аватар для voraa
Профессор
Отправить личное сообщение для voraa Посмотреть профиль Найти все сообщения от voraa
 
Регистрация: 03.02.2020
Сообщений: 2,701

Я думаю, если бы было возможно, то были бы и примеры этого.
Ответить с цитированием
  #3 (permalink)  
Старый 10.01.2023, 18:59
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

ureech,
если оглавления нет, делишь высоту текста на высоту просмотра, получаешь количество кнопок, на каждую кнопку цепляешь нужную величину прокрутки, если кнопок только две, верх и низ, тогда к текущей прокрутке , прибавляешь/вычитаешь высоту просмотра.
Ответить с цитированием
  #4 (permalink)  
Старый 10.01.2023, 19:56
Профессор
Отправить личное сообщение для ureech Посмотреть профиль Найти все сообщения от ureech
 
Регистрация: 11.03.2013
Сообщений: 765

Сообщение от рони
делишь высоту текста на высоту просмотра, получаешь количество кнопок
Это хорошо. Но дальше нет. Вы описываете скролинг по вертикали. А нужен смена страниц. То есть по горизонтали. Пагинация
Ответить с цитированием
  #5 (permalink)  
Старый 10.01.2023, 19:57
Профессор
Отправить личное сообщение для ureech Посмотреть профиль Найти все сообщения от ureech
 
Регистрация: 11.03.2013
Сообщений: 765

Хотя, если будет количество кнопок, то уже легче) Но весь вопрос в том как получить всю высоту текста. Как то считать все символы не хотелось бы. И конечно есть оглавление)

Последний раз редактировалось ureech, 10.01.2023 в 20:06.
Ответить с цитированием
  #6 (permalink)  
Старый 10.01.2023, 20:21
Профессор
Отправить личное сообщение для ureech Посмотреть профиль Найти все сообщения от ureech
 
Регистрация: 11.03.2013
Сообщений: 765

Ааа, понял про высоту)
Ответить с цитированием
  #7 (permalink)  
Старый 10.01.2023, 21:04
Аватар для voraa
Профессор
Отправить личное сообщение для voraa Посмотреть профиль Найти все сообщения от voraa
 
Регистрация: 03.02.2020
Сообщений: 2,701

Ну вот что то такое.
Недостаток - режет строки. Верхняя часть строки на предыдущей странице, нижняя на следующей.
<!DOCTYPE>
<html>
<head>
    <style>
        #page {
            position: relative;
            width:300px;
            height:600px;
            overflow: hidden;
            border: 1px solid blue;
            padding: 10px;
        }
        #paginator {
            display: flex;
        }
    </style>

</head>
<body>

<div id=page>
</div>

<div id="paginator"></div>
<script>
    const text = `
<h2>Introduction</h2>
<p>This Ecma Standard defines the ECMAScript 2023 Language. It is the
fourteenth edition of the ECMAScript Language Specification.
Since publication of the first edition in 1997, ECMAScript has
grown to be one of the world's most widely used general-purpose programming languages.
It is best known as the language embedded in web browsers but has also been widely adopted
for server and embedded applications.  
<p>ECMAScript is based on several originating technologies, the most well-known being
JavaScript (Netscape) and JScript (Microsoft). The language was invented by Brendan
Eich at Netscape and first appeared in that company's Navigator 2.0 browser.
It has appeared in all subsequent browsers from Netscape and in all browsers
from Microsoft starting with Internet Explorer 3.0.
<p>The development of the ECMAScript Language Specification started in November 1996.
The first edition of this Ecma Standard was adopted by the Ecma General Assembly of June 1997.
<p>That Ecma Standard was submitted to ISO/IEC JTC 1 for adoption under the fast-track procedure,
and approved as international standard ISO/IEC 16262, in April 1998. The Ecma General
Assembly of June 1998 approved the second edition of ECMA-262 to keep it fully aligned with
ISO/IEC 16262. Changes between the first and the second edition are editorial in nature.
    
<p>The third edition of the Standard introduced powerful regular expressions,
better string handling, new control statements, try/catch exception handling,
tighter definition of errors, formatting for numeric output and minor changes
in anticipation of future language growth. The third edition of the ECMAScript
standard was adopted by the Ecma General Assembly of December 1999 and published
as ISO/IEC 16262:2002 in June 2002.
    
<p>After publication of the third edition, ECMAScript achieved massive adoption
in conjunction with the World Wide Web where it has become the programming
language that is supported by essentially all web browsers. Significant work
was done to develop a fourth edition of ECMAScript. However, that work was not
completed and not published as the fourth edition of ECMAScript but some of it was
incorporated into the development of the sixth edition.
    
<p>The fifth edition of ECMAScript (published as ECMA-262 5th edition) codified de
facto interpretations of the language specification that have become common among
browser implementations and added support for new features that had emerged since the
publication of the third edition. Such features include accessor properties,
reflective creation and inspection of objects, program control of property
attributes, additional array manipulation functions, support for the JSON
object encoding format, and a strict mode that provides enhanced error checking
and program security. The fifth edition was adopted by the Ecma General Assembly of December 2009.
    
<p>The fifth edition was submitted to ISO/IEC JTC 1 for adoption under the fast-track
procedure, and approved as international standard ISO/IEC 16262:2011. Edition 5.1
of the ECMAScript Standard incorporated minor corrections and is the same text as
ISO/IEC 16262:2011. The 5.1 Edition was adopted by the Ecma General Assembly of June 2011.
    
<p>Focused development of the sixth edition started in 2009, as the fifth edition
was being prepared for publication. However, this was preceded by significant
experimentation and language enhancement design efforts dating to the publication
of the third edition in 1999. In a very real sense, the completion of the sixth
edition is the culmination of a fifteen year effort. The goals for this edition
included providing better support for large applications, library creation,
and for use of ECMAScript as a compilation target for other languages. Some
of its major enhancements included modules, class declarations, lexical
block scoping, iterators and generators, promises for asynchronous programming,
destructuring patterns, and proper tail calls. The ECMAScript library of
built-ins was expanded to support additional data abstractions including maps,
sets, and arrays of binary numeric values as well as additional support
for Unicode supplementary characters in strings and regular expressions.
The built-ins were also made extensible via subclassing. The sixth
edition provides the foundation for regular, incremental language and library
enhancements. The sixth edition was adopted by the General Assembly of June 2015.
`
    const page = document.getElementById('page');
    const paginator = document.getElementById('paginator');
    page.innerHTML = text;
    let pageheight = page.clientHeight;
    let textheight = page.scrollHeight;
    const nbutton = ((textheight / pageheight) |0) +1;
    let y = 0;
    const pagebeg = [];
    for (let i = 0; i < nbutton; i++){
        pagebeg.push(y);
        y += pageheight;
        const button = document.createElement('button');
        button.dataset.npag = '' + i;
        button.textContent = i+1;
        paginator.append(button);
    }
    paginator.addEventListener('click', ({target}) => {
        if (target.nodeName != 'BUTTON') return;
        const nbutton = target.dataset.npag;
        const beg = pagebeg[nbutton];
        page.scrollTo(0, beg);
    })
</script>
</body>
</html>

Надо еще делать пересчет при ресайзе. А как сделать, что бы при ресайзе остаться на том же (хотя бы приблизительно) месте, я без понятия.

Последний раз редактировалось voraa, 11.01.2023 в 07:14.
Ответить с цитированием
  #8 (permalink)  
Старый 10.01.2023, 22:05
Профессор
Отправить личное сообщение для ureech Посмотреть профиль Найти все сообщения от ureech
 
Регистрация: 11.03.2013
Сообщений: 765

voraa, спасибо за пример. завтра гляну. Сегодня голова уже не варит). Я уже вывел количество кнопок,их тоже js рисует. Завтра буду с прокруткой и пагинацией разбираться. Надеюсь ваш пример поможет). С обрезанием строк думаю решить путём расчёта высоты строки. Насчёт ресайза пока не понял).
Ответить с цитированием
  #9 (permalink)  
Старый 11.01.2023, 11:11
Профессор
Отправить личное сообщение для ureech Посмотреть профиль Найти все сообщения от ureech
 
Регистрация: 11.03.2013
Сообщений: 765

voraa,
А что такое npag в 103 стр.?
Ответить с цитированием
  #10 (permalink)  
Старый 11.01.2023, 11:25
Аватар для voraa
Профессор
Отправить личное сообщение для voraa Посмотреть профиль Найти все сообщения от voraa
 
Регистрация: 03.02.2020
Сообщений: 2,701

Сообщение от ureech
А что такое npag в 103 стр.?
Я для каждой кнопки устанавливаю атрибут data-npag="<номер станицы.>" (номера от нуля). Т.к я делегирую обработку клика на paginator, мне там надо знать на какую именно кнопку нажали. Там (в стр. 109) я читаю этот номер.

dataset https://developer.mozilla.org/en-US/...lement/dataset

Последний раз редактировалось voraa, 11.01.2023 в 11:27.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как ускорить индексацию страниц, которые создаются фильтром? baustof Общие вопросы Javascript 0 06.12.2021 17:18
Пагинация на JS orloff Общие вопросы Javascript 2 30.10.2020 20:57
Спарсить несколько страниц (Google Chrome Extension) libertyswift Javascript под браузер 6 20.01.2017 10:43
Пагинация, создание массива страниц osdohtem jQuery 0 25.11.2014 13:25
Поиск страниц по ключевым словам stormageddon Events/DOM/Window 5 22.06.2013 21:09