11

假设我有一个非常长的内容页面,其中包含多个段落,这些段落无法在带有垂直滚动条的单个浏览器窗口中显示

<p>...very long sentence ...</p>
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>

所以我想剪切段落并将它们格式化为多个页面,例如

<!-- page 1 -->
<p>...very long sentence ...</p>
<p>...very long </p><!-- the ending p tag is automatic inserted since the following text cannot be displayed -->

<!-- page 2 -->
<p>sentence ...</p>
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>

是否有用于此目的的现有脚本?

在极端情况下,段落可能包含图像,因此每行的高度可能会有所不同。

4

10 回答 10

20

有人用 jQuery 创建了显示/隐藏功能。

这可能会对您有所帮助。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Example: Show more, less using jQuery</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <style type="text/css">
        a.moreText
        {
            color: blue;
            cursor: pointer;
            padding-left: 5px;
            padding-right: 10px;
        }

        a.lessText
        {
            cursor: pointer;
            color: blue;
            display: none;
            padding-left: 5px;
            padding-right: 10px;
        }

        span.secondHalf
        {
            display: none;
        }
    </style>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("p").each(function () {
                SetMoreLess(this, 350, 20, " ... more", " ... less");
            });

            $("a.moreText").click(function () {
                $(this).hide();
                var pTag = $(this).parents("p.summary");

                $(pTag).find("a.lessText").show();
                $(pTag).find("span.secondHalf").show();
            });

            $("a.lessText").click(function () {
                $(this).hide();
                var pTag = $(this).parents("p.summary");

                $(pTag).find("a.moreText").show();
                $(pTag).find("span.secondHalf").hide();
            });
        });

        function SetMoreLess(para, thrLength, tolerance, moreText, lessText) {
            var alltext = $(para).html().trim();

            $(para).addClass("summary");        // this class is added to identify the p tag, when more/less links are clicked

            if (alltext.length + tolerance < thrLength) {
                return;
            }
            else {
                var firstHalf = alltext.substring(0, thrLength);
                var secondHalf = alltext.substring(thrLength, alltext.length);

                var firstHalfSpan = '<span class="firstHalf">' + firstHalf + '</span>';
                var secondHalfSpan = '<span class="secondHalf">' + secondHalf + '</span>';
                var moreTextA = '<a class="moreText">' + moreText + '</a>';
                var lessTextA = '<a class="lessText">' + lessText + '</a>';

                var newHtml = firstHalfSpan + moreTextA + secondHalfSpan + lessTextA;

                $(para).html(newHtml);
            }
        }
    </script>
</head>
<body>
    <div id="lipsum">

        <p>
            Integer consectetur, dui ut lobortis aliquet, leo est ullamcorper augue, id blandit
            metus libero eu leo. Pellentesque dui sapien, tempus ultricies ultricies nec, molestie
            at eros. Integer facilisis luctus libero quis accumsan. Suspendisse eu velit ac
            erat iaculis pellentesque vel mollis est. Cras ac erat vulputate augue tincidunt
            euismod a eu diam. Pellentesque habitant morbi tristique senectus et netus et malesuada
            fames ac turpis egestas. Nullam sed arcu lorem. Cras porta dui in lorem tempor dapibus.
            Ut magna metus, tincidunt et sodales pretium, aliquam ac ligula. Etiam at enim id
            enim rhoncus scelerisque. Fusce porta, arcu non malesuada consequat, massa lectus
            feugiat diam, aliquam convallis neque mauris eu urna. Nulla pellentesque eleifend
            lectus, vel sodales leo consequat vestibulum. Sed elementum, lorem ac mollis mattis,
            purus dolor interdum neque, ac rutrum nisl elit eu arcu. Curabitur risus arcu, suscipit
            dignissim hendrerit at, luctus nec mauris. Pellentesque accumsan euismod sem nec
            feugiat. Nullam faucibus gravida elit, nec facilisis lorem ullamcorper nec.
        </p>
        <p>
            Vestibulum tincidunt lacus sit amet justo blandit vehicula. In pretium sem quis
            ligula ultricies eget sodales velit mollis. Phasellus facilisis varius enim, non
            rutrum nulla scelerisque eu. Curabitur posuere quam eget dui dignissim sed placerat
            ante tincidunt. Suspendisse faucibus vulputate est quis feugiat. Nulla nec ante
            a enim molestie consectetur. In hac habitasse platea dictumst. Donec tincidunt lacinia
            pellentesque. Integer hendrerit ligula non nibh posuere pretium. Sed tincidunt tincidunt
            lectus, non consectetur est iaculis sit amet. Morbi vel lobortis ligula. Sed scelerisque
            varius interdum. In sollicitudin lorem et mauris luctus venenatis commodo nunc venenatis.
            Praesent vitae justo nisl.
        </p>
        <p>
            Nulla posuere ante vel quam dapibus fringilla. In elementum mi interdum nisl vehicula
            eu iaculis felis pretium. Ut id massa eget turpis gravida luctus et non nunc. Etiam
            viverra suscipit mauris quis scelerisque. Vestibulum tempor neque nisl, nec aliquam
            nibh. Quisque cursus faucibus libero sit amet placerat. Nulla id blandit ligula.
            Nullam aliquam dui at justo facilisis accumsan. Morbi vel arcu id mi mollis vestibulum.
            Praesent imperdiet, lectus eget adipiscing lobortis, urna enim vulputate lorem,
            et bibendum turpis arcu quis ligula. Donec ultricies sollicitudin imperdiet. Mauris
            a augue nulla. Donec sagittis est magna, sed scelerisque magna. Nam tincidunt, felis
            quis luctus sodales, orci ligula consequat massa, a pulvinar leo urna id dui. In
            sit amet augue est, et tincidunt metus. Quisque pellentesque, felis vel semper ullamcorper,
            leo nulla eleifend nunc, et suscipit massa tellus non tellus.
        </p>
        <p>
            Etiam accumsan, diam semper mattis tempus, sapien erat cursus dui, venenatis convallis
            metus lectus at arcu. Duis eget dolor nec metus laoreet aliquam. Nulla eu viverra
            massa. Vestibulum id urna ante, at aliquam augue. Cum sociis natoque penatibus et
            magnis dis parturient montes, nascetur ridiculus mus. Nulla risus felis, convallis
            at sagittis nec, fringilla in lacus. Integer at fermentum enim. Nullam lacinia eleifend
            nisi, laoreet porta nunc elementum ut. Nulla facilisi.
        </p>
        <p>
            Fusce id orci dui. In nec tempor nulla. Fusce commodo cursus orci in feugiat. Fusce
            porttitor nulla sit amet arcu tempor nec viverra risus tempor. Pellentesque felis
            lectus, pellentesque dignissim interdum sed, aliquam eu urna. In molestie leo vel
            massa dapibus imperdiet. Ut risus odio, rutrum eu congue sit amet, pellentesque
            quis urna. Duis tempor magna eu nisl volutpat eget pulvinar ante rutrum. Morbi quis
            dolor lorem, sit amet pellentesque mauris. Nunc tellus tellus, consequat a pharetra
            eu, cursus eu dolor. Aliquam non dolor mauris. Vestibulum vel purus eu massa sollicitudin
            sollicitudin vel in mauris. Proin tristique, mi sed tempus facilisis, odio elit
            faucibus turpis, sed aliquam risus elit in urna.
        </p>
        <p>
            Suspendisse et libero tincidunt mauris pharetra hendrerit at ac nisl. Cras mauris
            ante, sodales at scelerisque in, ullamcorper sed ipsum. Praesent est erat, mollis
            eget ullamcorper quis, mattis ac nisi. Pellentesque habitant morbi tristique senectus
            et netus et malesuada fames ac turpis egestas. Etiam vulputate, lacus non iaculis
            euismod, urna eros fringilla leo, a faucibus enim metus sed nibh. Etiam sagittis
            sodales porttitor. Aliquam consequat lacus sed enim scelerisque vel malesuada sapien
            viverra. Nulla massa metus, dignissim at consectetur sed, elementum nec massa. Phasellus
            cursus, odio sagittis molestie aliquam, est mi volutpat nibh, nec ullamcorper lacus
            mi sit amet nulla. Vivamus pellentesque, nulla ut pretium pretium, massa justo malesuada
            nibh, a adipiscing diam enim eget elit. Phasellus nec sapien id elit lobortis sodales
            vel ut neque. Sed ultricies tincidunt hendrerit. Vestibulum at velit diam, in sollicitudin
            eros. Cras tincidunt tincidunt orci, id hendrerit lorem porttitor a.
        </p>

        <p>
            Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
            mus. Ut tortor quam, sodales a egestas ac, consectetur vitae eros. Suspendisse sit
            amet libero ac magna sagittis tincidunt. Quisque a risus orci. Etiam nec velit tortor,
            sed interdum nulla. Mauris nec lorem tortor, a dapibus mi. Sed posuere tempor magna
            vitae consequat.
        </p>
        <p>
            Nam ornare massa a velit congue ut con</p>
        <p>
            Nulla sed magna sed lectus imperdiet sagittis sed at nunc. Duis ornare tortor in
            eros rhoncus quis tempor justo congue. Proin ut suscipit augue. Sed consectetur
            arcu eget purus condimentum venenatis. Pellentesque dui orci, malesuada ut fringilla
            et, tincidunt quis est. Pellentesque ipsum metus, pulvinar sit amet accumsan non,
            imperdiet non enim. Donec leo lorem, pharetra at eleifend id, malesuada ut enim.
            Proin ligula risus, pretium eget adipiscing a, sagittis et tellus. Duis dictum tristique
            pretium. Sed mattis neque vitae augue aliquet dictum. Proin ut tempus velit. Donec
            tincidunt hendrerit risus, vel imperdiet libero interdum ut. Phasellus rutrum sem
            a urna semper et fermentum purus mattis. Aliquam euismod tempor dapibus. Maecenas
            ultrices magna at ligula ultrices at accumsan erat sagittis. Ut neque ante, scelerisque
            ut laoreet egestas, tempus ut erat.
        </p>
    </div>
</body>
</html>

如果段落带有图像和其他 html 标签,请使用以下逻辑:

<div style="height:500px;overflow:hidden" id="blah">
Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.
</div>
<a href="#" id="showmore">Show more</a>
<script>
$("#showmore").live('click', function() {
   $("#blah").css('height','1000px');

});
</script>
于 2012-08-24T05:26:05.803 回答
7

编辑:(演示链接更新

看这个演示

通过使用下面的代码,您可以根据需要对无限的段落进行分页。

jQuery:

    $(document).ready(function(){

        //how much items per page to show
        var show_per_page = 5; 
        //getting the amount of elements inside content div
        var number_of_items = $('#content').children().size();
        //calculate the number of pages we are going to have
        var number_of_pages = Math.ceil(number_of_items/show_per_page);

        //set the value of our hidden input fields
        $('#current_page').val(0);
        $('#show_per_page').val(show_per_page);

        //now when we got all we need for the navigation let's make it '

        /* 
        what are we going to have in the navigation?
            - link to previous page
            - links to specific pages
            - link to next page
        */
        var navigation_html = '<a class="previous_link" href="javascript:previous();">Prev</a>';
        var current_link = 0;
        while(number_of_pages > current_link){
            navigation_html += '<a class="page_link" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
            current_link++;
        }
        navigation_html += '<a class="next_link" href="javascript:next();">Next</a>';

        $('#page_navigation').html(navigation_html);

        //add active_page class to the first page link
        $('#page_navigation .page_link:first').addClass('active_page');

        //hide all the elements inside content div
        $('#content').children().css('display', 'none');

        //and show the first n (show_per_page) elements
        $('#content').children().slice(0, show_per_page).css('display', 'block');

    });​

    function previous(){

        new_page = parseInt($('#current_page').val()) - 1;
        //if there is an item before the current active link run the function
        if($('.active_page').prev('.page_link').length==true){
            go_to_page(new_page);
        }

    }

    function next(){
        new_page = parseInt($('#current_page').val()) + 1;
        //if there is an item after the current active link run the function
        if($('.active_page').next('.page_link').length==true){
            go_to_page(new_page);
        }

    }
    function go_to_page(page_num){
        //get the number of items shown per page
        var show_per_page = parseInt($('#show_per_page').val());

        //get the element number where to start the slice from
        start_from = page_num * show_per_page;

        //get the element number where to end the slice
        end_on = start_from + show_per_page;

        //hide all children elements of content div, get specific items and show them
        $('#content').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');

        /*get the page link that has longdesc attribute of the current page and add active_page class to it
        and remove that class from previously active page link*/
        $('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');

        //update the current page input field
        $('#current_page').val(page_num);
    }

HTML:

    <!-- the input fields that will hold the variables we will use -->
    <input type='hidden' id='current_page' />
    <input type='hidden' id='show_per_page' />

    <!-- Content div. The child elements will be used for paginating(they don't have to be all the same,
        you can use divs, paragraphs, spans, or whatever you like mixed together). '-->
    <div id='content'>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p>
        <p>and so on....</p>
    </div>

    <!-- An empty div which will be populated using jQuery -->
    <div id='page_navigation'></div>
于 2012-08-24T05:29:33.613 回答
2

不久前,我创建了pagify,一个 jQuery 插件来做到这一点。它通过将元素拆分为单词并逐步添加单词直到高度达到指定高度来检测页面高度。我给了它一些 CSS 让它看起来像下面演示中的页面,但你可以设置它的样式以使用 100% 的宽度和高度。你可以简单地调用它,$('body').pagify(options);默认选项如下

{
    'pageTag' : 'div', // the tag which surrounds each page
    'pageClass': 'page', // the class of the page tag
    'innerClass': 'page-inner', // the class of the inner page element
    'pageSize': 'A4', // a class added to the page so that the size can be defined by css
    'pageSizeClassPrefix': 'page-', // the prefix to the above class
    'pageOrientation': 'portrait', // not yet used, but could be used to flip width and height
    'splitElementClass': 'split-element' // elements which have been split across two pages are given this class
};

所以要使用 100% 的宽度和高度:

html, body, page-screen-size {
    width: 100%;
    height: 100%;
}

$('body').pagify({
    pageSize : 'screen-size'
});

这是在行动:http: //jsfiddle.net/nathan/nfHHE/

于 2012-08-29T18:04:26.440 回答
1

据我了解,这与在线阅读器的工作方式非常相似,其中内容被格式化为不同的页面或幻灯片,其中的内容无关紧要,因为这将适应其容器。

为了实现您的目标,我推荐 CSS3 多列布局(请参阅http://www.w3.org/TR/2001/WD-css3-multicol-20010118/

CSS

#your-container 
{ 
  width: 90%; 
  margin: 0 auto; 
  overflow: hidden; //Hide overflowing content
  padding: 20px 0; 
}

#div-inside-container //For padding and columns display purposes
{ 
  position: relative; 

  -moz-column-count: 1; 
  -webkit-column-count: 1; 
  column-count: 1; 

  -moz-column-width: 50em; 
  -webkit-column-width: 50em; 
  column-width: 50em; 

  -webkit-column-gap: 0; 
  -moz-column-gap: 0; 
  column-gap: 0; 
}

查询

$(window).resize(function() {

    //Resize container
    $(div_content).height(Dimensions.TellMeHeight() - padding);

});

请参阅示例和代码:http: //jsfiddle.net/GLbXX/1/

于 2012-08-29T09:52:15.850 回答
0

你可以使用 jqueryaccordion控件,如果你有多个段落而不是你应该在手风琴中划分,它将提高页面的可读性和外观

从这里阅读更多

于 2012-08-24T05:09:07.710 回答
0

《金融时报》开发了一种用于多栏布局的 JavaScript 解决方案,特别关注复杂的(即类似报纸的)案例FTColumnFlow

如果您将容器设置为一列的宽度,然后进行一些分页,即通过 jQuery UI 选项卡,这可能是一个解决方案,可以满足最困难的情况。

于 2012-08-29T12:42:20.450 回答
0

试试这个 jquery 插件 jqPaginationjPagination

于 2012-08-31T05:10:20.100 回答
0

Sugar.js 有一个很棒的 .truncate() 函数,可以根据你的规范裁剪文本

http://sugarjs.com/api/String/truncate

于 2012-08-29T16:44:14.193 回答
0

我希望这段代码对你有所帮助。也许有些情况被忽略了,或者你可以找到更好的算法或者你可以优化它。这只是一种引导你的方式。

$(document).ready(function(){
    var current_page_height = $(window).innerHeight() - $("div.pagination").innerHeight();

    function createPages(page_height){
        var current_page_height = 0;
        var pages = [];

        var current_page = [];
        var cpt_page = 0;

        $("div.content").children().each(function(index, element){
            var el = $(element);
            el.hide();

            if(current_page_height + el.innerHeight() > page_height){
                var height_over = (current_page_height+el.innerHeight()) - page_height;
                var line_height_el = el.css("line-height").replace("px","")

                if( line_height_el < height_over && el.find("img").length == 0){
                    var number_line_to_remove = Math.round(height_over/line_height_el);
                    var number_line = el.innerHeight() / line_height_el;
                    var char_by_line = Math.floor(el.html().length / number_line);
                    var content_el = el.html();
                    var pointer_substr = (number_line - number_line_to_remove) * char_by_line;

                    while(content_el.charAt(pointer_substr) != " " && pointer_substr > 0){
                        pointer_substr--;
                    }

                    var new_element = $("<p>" + content_el.substr( pointer_substr, content_el.length-1) + "</p>");
                    el.html( content_el.substr(0, pointer_substr+1));
                    current_page.push(el);
                    el.after(new_element);
                    el = new_element;
                    el.hide();
                }

                pages[cpt_page] = current_page;
                current_page_height = 0;
                current_page = [];
                cpt_page++;
            }
            current_page.push( el );
            current_page_height += el.innerHeight();
        });

        if(current_page.length > 0){
            pages[cpt_page] = current_page;
        }

        return pages;
    }

    function displayPage(page_to_display){
        if( page_to_display >= 0 && page_to_display < pages.length){
            $(pages[page_to_display]).each(function(index, element){
                element.show();
            });

            $(pages[$("span.page").html()]).each(function(index,element){
                element.hide();
            });
            $("span.page").html(page_to_display);
        }
    }

    var pages = createPages(current_page_height);
    displayPage(0);

    $("span.next").click(function(){
       var page = new Number($("span.page").html());
       displayPage( page+1 );
    });

    $("span.prev").click(function(){
       var page = new Number($("span.page").html());
       displayPage( page-1 );
    });

});

你可以在这里找到一个例子

于 2012-08-29T14:42:06.853 回答
-2

看看CSS 中的:before:after伪元素(对不起,我不能更具体,我自己还在探索之路上)

于 2012-08-21T07:09:45.207 回答