我正在尝试使用JavaScript创建分页系统。
基本情况:我有一个数据库,它包含相当长的文本(故事章节,5000字+)。我想在网站上展示这些章节......但不是一次写完整篇文章,因为这样会大大降低可读性,但是会在页面中出现。
我没有问题显示的文字,而是让页面正确。
我一直在环顾四周,并且遇到了一个JQuery代码,这个代码的功能与我想要的一样。但是这个方法有一个重要的警告。完成文本分页大约需要10秒钟,这是等待太久的时间。
代码基本上做了什么:
它将文本分割成单词(用空格分隔)。
然后尝试将一个单词添加到innerHTML中,检查文本现在是否大于它应该适合的容器。
每次它打破边界时,它都会回到前一个字符串并创建一个新页面。 (通过将文本封装到跨度中,然后可以在需要的时候隐藏/显示)。但是这种方法太慢了,因为它必须运行这些检查5000次以上。
我试图创建一个近似系统,它基本上占用了大量的单词,将它除以系数0.5,检查缓冲区是否大于所需的大小,并重复此过程,直到缓冲区小于所需大小这是第一次,从那个位置开始,它会填满缓冲区,直到它满了。
然而,它似乎并没有正确工作(双字,行,这些字不完整,但仍然太慢。)
这是我目前使用的代码,我会很感激任何修复和建议如何使它更容易,尤其是:更快。
哦和:不,分页服务器不是一种选择,因为它应该适合可变浏览器格式......在1280x768分辨率的全屏浏览器中,它将少于1024x768分辨率的小浏览器。
function CreateChild(contentBox, Len, pageText, words) {
var Child = document.createElement("span");
Child.innerHTML = pageText;
contentBox.appendChild(Child);
if(Len == 0) ++Len;
words.splice(0, Len);
return words.length;
}
$(document).ready(function(){
var src = document.getElementById('Source');
var contentBox = document.getElementById('content');
var inner = document.getElementById('inner');
//get the text as an array of word-like things
var words = src.innerHTML.replace(/ +/g, " ").split(' '), wCount = words.length;
//start off with no page text
var pageText = null, cHeight = contentBox.offsetHeight;
while(words.length > 0) {
var Found = false;
pageText = words[0]; //Prevents constant checking for empty
wCount *= 0.5; //Searches, until the words fit in.
for(var i = 1; i < wCount; ++i) pageText += ' ' + words[i];
inner.innerHTML = pageText;
Distance = inner.offsetHeight - cHeight;
if(Distance < 40) { //Less than two lines
wCount = Math.floor(wCount);
if(Distance < 0) { //Already shorter than required. Fill.
for(var i = wCount; i < words.length; ++i) {
//add the next word to the pageText
var betterPageText = pageText + ' ' + words[i];
inner.innerHTML = betterPageText;
//Checks, whether the new words makes the buffer too big.
if(inner.offsetHeight > cHeight) {
wCount = CreateChild(contentBox, i, pageText, words);
Found = true;
break;
} else {
//this longer text still fits
pageText = betterPageText;
}
}
} else {
for(var i = wCount; i >= 0; --i) {
//Removes the last word from the text
var betterPageText = pageText.slice(0, pageText.length - words[i].length - 1);
inner.innerHTML = betterPageText;
//Is the text now short enough?
if(inner.offsetHeight <= cHeight) {
wCount = CreateChild(contentBox, i, pageText, words);
Found = true;
break;
} else {
pageText = betterPageText;
}
}
}
if(!Found) CreateChild(contentBox, i, pageText, words);
}
}
//Creates the final block with the remaining text.
Child = document.createElement("span");
Child.innerHTML = pageText;
contentBox.appendChild(Child);
//Removes the source and the temporary buffer, only the result remains.
contentBox.removeChild(inner);
src.parentNode.removeChild(src);
//The rest is the actual pagination code, but not the issue
});