The requirement received when reading the h5 page embedded in the official account is to realize the paging and page turning of the novel, and the page cannot have scroll bars. I read some on the Internet, there is not a lot of information, I will write it myself~
First, calculate the total number of pages according to the length of the article:
// Paging function pagesCell(){ allpages = Math.ceil(parseInt($("#artical").prop("scrollHeight"))/parseInt($("#artical").prop("offsetHeight"))); //计算总页数 } function showPages(){ $('.pages').html(i+'/'+allpages); }
Then detect left and right sliding
$('#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); // Swipe left, flip forward the executed code } else if (pullDeltaX < -30 ){ if (i == allpages){ alert( 'last page' ); }else if(i < allpages){ i++; showpart(i); } //Swipe right, scroll back to the executed code } })
});
Finally realize the page turn
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();
}
In this way, the basic needs are realized. The fly in the ointment is that the animation effect of page turning on the app is not realized. Continue to work hard~