移动端 js 实现文章的分页、翻页

在做一个阅读公众号内嵌的h5页面时接到的需求是实现小说的分页、翻页,页面不能出现滚动条。上网看了些,资料不是很多呀,自己写个呗~

先是根据文章的长短计算总页数:

//分页
function pagesCell(){  
    allpages = Math.ceil(parseInt($("#artical").prop("scrollHeight"))/parseInt($("#artical").prop("offsetHeight"))); 
   //计算总页数
} 
function showPages(){
    $('.pages').html(i+'/'+allpages);
}

再检测左右滑动

$('#artical').on('touchstart', function (e) {
    $tb = $(this);
    var startX = e.originalEvent.changedTouches[0].clientX,
    pullDeltaX = 0;

    $tb.on('touchmove', function (e) {
        var x = e.originalEvent.changedTouches[0].clientX;
        pullDeltaX = x - startX;
        if (!pullDeltaX){
            return;
        }
        e.preventDefault();
    });
    $tb.on('touchend', function (e) {
        $tb.off('touchmove touchend');
        e.stopPropagation();
        if (pullDeltaX > 30 && allpages > 1 && i>1){
           i--;
           showpart(i);
           //左滑,往前翻所执行的代码
        }
        else if (pullDeltaX < -30){
             if(i == allpages){
                 alert('最后一页');
            }else if(i < allpages){
                  i++;
                 showpart(i);
              }
                //右滑,往后翻所执行的代码
        }

     })
});

最后实现翻页

function showpart(x){  
    var height = (x-1)*parseInt($("#artical").prop("offsetHeight"));
    if(parseInt(height/lineHeight) >= 0.5){
        $("#artical").prop("scrollTop",(parseInt(height/lineHeight))*lineHeight);  
    }else{
        $("#artical").prop("scrollTop",(parseInt(height/lineHeight)-1)*lineHeight);  
    }
    showPages();
}

这样就实现了基本的需求,美中不足的是没有实现app上翻页的动画效果,继续努力努力~

猜你喜欢

转载自www.cnblogs.com/bella-lin/p/8986195.html