Text pagination inside a DIV with image

后端 未结 4 1997
庸人自扰
庸人自扰 2021-01-16 15:00

I want to paginate a text in some div so it will fit the allowed area
Logic is pretty simple:
1. split text into words
2. add word by word into and calculate el

4条回答
  •  自闭症患者
    2021-01-16 15:30

    Solved by using jQuery.clone() method and performing all calculations on hidden copy of original HTML element

    function paginate() {
    
         var section = $('.section');
    
         var cloneSection = section.clone().insertAfter(section).css({ position: 'absolute', left: -9999, width: section.width(), zIndex: -999 });
    
         cloneSection.css({ width: section.width() });
    
         var descBox = cloneSection.find('.holder-description').css({ height: 'auto' });
    
         var newPage = $('
    ');
         contentBox.empty();
         descBox.empty();
         var betterPageText = '';
         var pageNum = 0;
         var isNewPage = false;
    
         var lineHeight = parseInt(contentBox.css('line-height'), 10);
    
         var wantedHeight = contentBox.height() - lineHeight;
         var oldText = '';
    
         for (var i = 0; i < words.length; i++) {
            if (isNewPage) {
               isNewPage = false;
               descBox.empty();
            }
            betterPageText = betterPageText + ' ' + words[i];
    
            oldText = betterPageText;
    
            descBox.text(betterPageText + ' ...');
            if (descBox.height() >= wantedHeight) {
    
               if (i != words.length - 1) {
                  pageNum++;
    
                  if (pageNum > 0) {
                     betterPageText = betterPageText + ' ...';
                  }
    
                  oldText += ' ... ';
               }
    
               newPage.text(oldText);
               newPage.clone().appendTo(contentBox);
    
               betterPageText = '... ';
               isNewPage = true;
            } else {
               descBox.text(betterPageText);
               if (i == words.length - 1) {
                  newPage.text(betterPageText).appendTo(contentBox);
               }
            }
         }
    
         if (pageNum > 0) {
            contentBox.craftyslide({ height: wantedHeight });
         }
    
         cloneSection.remove();
    }
    

    live demo: http://jsfiddle.net/74W4N/19/

提交回复
热议问题