针对百度编辑器做的文章自动分页js

发布时间:2016-03-16 浏览次数:3929 文章来源:个人博客

原理:百度编辑器umeditor 对于文章内容来说,每个段落都会在前面加入一个<p>标签,可以利用这个<p>标签进行分页。


步骤:1、文章中有多少个<p>标签:$("showContent  p").length;其中("showContent  p")是标签数组

          2、循环每个<p>标签,获取每个<p>标签的滚动高度: $("#showContent p")[i].scrollHeight;其中i是个数

          3、从第一个<p>的标签高度开始加,如果和大于980(文章高度),那么就分页,即将其设置为第一小组;依次类推,将文章的<p>全部分组

          4、根据上面的分组即可知道文章有多少页,一组就是一页!然后点击第几页就是第几组显示,其他的隐藏!

          5、小提示:为了防止到最后一页高度低,造成分页网上跑,可以设置文章的最小高度:min-height   ; 如min-height : 980px

代码如下:


js部分:

$(function() {
    var Relative_len = 0;
    var group_no = 1;
    for (var i = 0; i < $("#showContent p").length; i++) { //循环每个<p>标签,获取每个<p>标签的长度
        if (Relative_len > 980) {  //设置大于980就分页
            Relative_len = $("#showContent p")[i].scrollHeight; 
            group_no++;
            $("#showContent p")[i].className  = "pagegroup_" + group_no; 
        } else {
            Relative_len = $("#showContent p")[i].scrollHeight + Relative_len;
            $("#showContent p")[i].className  = "pagegroup_" + group_no;
        }
    }
    if (group_no > 1) {
        $("#showContent p").hide();
        $("#showContent p.pagegroup_1").show();
        var current = 1;
        var previous = 1, next = 2, pageIndex = 1;
        var html = "<a href=\javascript:void(0);   data-id=" + previous + " id='page_previous' ><</a> ";
        for (var i = 1; i <= group_no; i++) {
            if (i == 1) {
                html += " <a href=\javascript:void(0); class='currentp' id='page" + i + "' data-id=" + i + " > " + i + "</a> ";
            } else {
                html += " <a href=\javascript:void(0); id='page" + i + "' data-id=" + i + " > " + i + "</a> ";
            }
        }
        html += " <a href=\javascript:void(0);  data-id=" + next + " id='page_next' >></a> ";
        html += " <a href=\javascript:void(0); >在本页阅读全文</a> ";
        $("#articlePages").html(html);
    }
    $("#articlePages a").click(function() {
        pageIndex = $(this).attr("data-id");
        if (pageIndex) {
            current = pageIndex;
            $(".currentp").attr("class", "");
            $("#page" + pageIndex).attr("class", "currentp");
            $("#showContent p").hide();
            $("#showContent p.pagegroup_"+ pageIndex).show();
            if (current > 1) {
                previous = parseInt(current) - parseInt(1);
                $("#page_previous").attr("data-id", previous);
            } else {
                previous = 1;
                $("#page_previous").attr("data-id", previous);
            }
            if (current < group_no) {
                next = parseInt(current) + parseInt(1);
                $("#page_next").attr("data-id", next);
            } else {
                next = group_no;
                $("#page_next").attr("data-id", next);
            }
        } else {
            $("#showContent p").show();
            $("#articlePages").hide();
        }
    })
});


key-word
百度编辑器文章分页 文章自动分页 js文章分页 编辑器文章自动分页