本文介绍了每2500个字符在< div>中换行使用PHP或javascript进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一长串文字.我想将此文本的每2500个字符包装到<div>中,以便可以对其进行分页.

I have a long block of text. I'd like to wrap every 2500 characters of this text into a <div> such I could do pagination on it.

以下内容无效:

//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>结束标记来使此工作生效.

Obviously I need the closing </div> tag to make this work.

有人在PHP或Javascript/jQuery中对此有何建议?

Does anyone have a suggestion for this in PHP or Javascript/jQuery?

推荐答案

然后添加</div>吗?

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


但是,您可以使用javascript做得更好:您可以根据观众的屏幕尺寸进行分页.

只需将HTML设置为:

Just set your HTML to:

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

为页面添加一些CSS:

Add some css for pages:

#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,则向后兼容.

This will work in conjunction with the PHP solution, providing backwards compatibility if javascript is disabled.

这篇关于每2500个字符在&lt; div&gt;中换行使用PHP或javascript进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:39