Split text into pages and present separately (HTML5)

前端 未结 6 1651
梦如初夏
梦如初夏 2020-12-03 03:27

Let\'s say we have a long text like Romeo & Juliet and we want to present this in a simple ereader (no animations, only pages and custom font-size). What approaches exis

6条回答
  •  旧巷少年郎
    2020-12-03 04:09

    Another idea is using CSS column to split html content, this reflow is done by browser it self so it will be very fast, the next step is inserting each page content into dom, I have done this by duplicating whole column and scroll each page to the cropped window, see codepen example:

    https://codepen.io/alphakevin/pen/eXqbQP

    const pageWidth = 320;
    const content = document.getElementById('content');
    const totalWidth = content.scrollWidth;
    const totalPages = totalWidth / pageWidth;
    console.log('totalPages', totalPages);
    
    let contentVisible = true;
    const button = document.getElementById('btn-content');
    const buttonText = document.getElementById('btn-content-text');
    const showHideContent = () => {
      contentVisible = !contentVisible;
      content.style.display = contentVisible ? 'block' : 'none';
      buttonText.innerText = contentVisible ? 'Hide' : 'Show';
    }
    button.addEventListener('click', showHideContent);
    
    const html = content.innerHTML;
    const container = document.getElementById('container');
    // console.log('content', content);
    for (let p = 0; p < totalPages; p++) {
      const page = document.createElement('div');
      page.innerHTML = html;
      page.className = 'page';
      page.style.cssText = `
        width: ${totalWidth}px;
        transform: translateX(-${p * pageWidth}px);
      `;
      const pageClip = document.createElement('div');
      pageClip.className = 'page-clip';
      pageClip.appendChild(page);
      const pageWrapper = document.createElement('div');
      pageWrapper.className = 'page-wrapper';
      pageWrapper.appendChild(pageClip);
      container.appendChild(pageWrapper);
    }
    
    showHideContent();
    

    This is very suitable for few paged content, but not OK for large content, you will get alot of wasted DOM element that will never be shown.

    But I think there must be better ideas like combining other answers, using javascript to help splitting column result.

    For reference, check paged media solution

    https://codepen.io/julientaq/pen/MBryxr

提交回复
热议问题