编程语言
首页 > 编程语言> > 使用PHP或javascript将每2500个字符的文本换行进行分页

使用PHP或javascript将每2500个字符的文本换行进行分页

作者:互联网

我有一长串文字.我想将这个文本的每2500个字符包装成一个< div>我可以对它进行分页.

以下不起作用:

//replace 2500 for 5 for purpose of this example
$text="sfdkjas;fakska;ldjk";
$text=wordwrap($text, 5, '<div class="individualPage">');

输出:

sfdkj<div class="individualPage">as;fa<div class="individualPage">kska;l<div
class="individualPage">djk

显然我需要结束< / div>标记使这项工作.

有没有人在PHP或Javascript / jQuery中有这个建议?

解决方法:

只需添加< / div>然后?

$text = '<div class="individualPage">'
      . wordwrap($text, 5, '</div><div class="individualPage">')
      . '</div>';

但是,你可以用javascript做得更好:你可以paginate in response to the viewer’s screen size.

只需将您的HTML设置为:

<div id="target">...</div>

为页面添加一些css:

#target {
    white-space: pre-wrap; /* respect line breaks */
}
.individualPage {
    border: 1px solid black;
    padding: 5px;    
}

然后使用以下代码:

var contentBox = $('#target');
//get the text as an array of word-like things
var words = contentBox.text().split(' ');

function paginate() {
    //create a div to build the pages in
    var newPage = $('<div class="individualPage" />');
    contentBox.empty().append(newPage);

    //start off with no page text
    var pageText = null;
    for(var i = 0; i < words.length; i++) {
        //add the next word to the pageText
        var betterPageText = pageText ? pageText + ' ' + words[i]
                                      : words[i];
        newPage.text(betterPageText);

        //Check if the page is too long
        if(newPage.height() > $(window).height()) {
            //revert the text
            newPage.text(pageText);

            //and insert a copy of the page at the start of the document
            newPage.clone().insertBefore(newPage);

            //start a new page
            pageText = null;
        } else {
            //this longer text still fits
            pageText = betterPageText;             
        }
    }    
}

$(window).resize(paginate).resize();

这将与PHP解决方案结合使用,如果禁用javascript,则提供向后兼容性.

标签:javascript,php,jquery,pagination,word-wrap
来源: https://codeday.me/bug/20190725/1538336.html