有没有办法弄清楚浏览器在已知大小的容器内每行显示的字符数?
所以我有一个已知维度的矩形,recX
和recY
,FONT_SIZE
的预定义13
。
我正在尝试计算这样一个段落的高度:
rectX
除以FONT_SIZE
以获取每行显示的字符数。FONT_SIZE
以获得它的显示高度。问题是,对于宽度为650像素的容器(测试用例),650/13的结果是50,但浏览器每行显示大约100个字符,它不会坚持任何默认值。我正在使用font-family:Lucida Console Monospace 13px, line-height:1em
。
守则
var width = Math.floor(this.articleSize.width / this.FONT_SIZE);
// this.article.paragraphs is an array of paragraphs without <p> or </p>.
for (var i = 0, ii = this.article.paragraphs.length; i < ii; i++) {
// based on the above compute the height/number of rows for each paragraph.
// This is a basic matrix approach.
// For those of you not familiar with the Closure Library, the goog.math.Size obj
// is a (width, height) object.
this.article.sizes[i] = new goog.math.Size(width, Math.ceil(this.article.paragraphs[i].length / width * this.FONT_SIZE));
};
var i = 0, currentPage = 0, pg = [], height = this.articleSize.height - 20, ii = this.article.paragraphs.length;
while (i < ii) {
// So here based on the height I am trying to see how many paragraphs
// Can fit into one 'page'. The navigation is horizontal, with a book like
// animation.
if((height - this.article.sizes[i].height) > 0) {
pg.push('<p>' + this.article.paragraphs[i] + '</p>');
height -= this.article.sizes[i].height;
i++;
} else {
this.article.pages[currentPage] = pg;
currentPage++;
pg = [];
height = this.articleSize.height - 20;
};
};
这必须适用于任何分辨率/视口大小,这意味着页面是在运行时计算的,并且整个过程在每个调整大小上再次完成,这与当前大小不同,任何方式都超过50个像素。
这是解决方法
project.MainArticle.loader.prototype.divideText = function(articleText) {
articleText = goog.string.collapseWhitespace(articleText);
articleText = articleText.replace(/<p><\/p>|• Comments will be turned on later/g, '').replace(/<p>\.<\/p>/g, '');
var trick = articleText.replace(/<p>/g, '<p class = \'trick-p\'>');
this.articleTextContainer.innerHTML = trick;
this.preAppendedParagraphs = goog.dom.getElementsByClass('trick-p');
for(var i = 0, ii = this.preAppendedParagraphs.length; i < ii; i++) {
this.article.sizes.push(+(this.preAppendedParagraphs[i]['offsetHeight'] + 10));
};
this.articleTextContainer.innerHTML = '';
this.article.paragraphs = articleText.replace(/<p>/g, '').split('</p>');
};
/**
* Divide the text into pages
* @private
*/
project.loader.prototype.createPages_ = function() {
var i = 0, currentPage = 0, pg = [], height = this.articleSize.height, ii = this.article.paragraphs.length - 1;
while(i < ii) {
if((height - this.article.sizes[i]) >= 0) {
pg.push('<p class=\'nz-ma-txt-p\'>' + this.article.paragraphs[i] + '</p>');
height -= this.article.sizes[i];
i++;
} else {
this.article.pages[currentPage] = pg;
currentPage++;
pg = [];
height = this.articleSize.height;
};
};
console.log(this.article);
};
答案 0 :(得分:1)
我认为您的问题可能是font-size=13px
并不意味着它使用13px进行显示。它在我的浏览器中使用大约8px(win7上的最新chrome)。因此,我创建了一个脚本来检测span中的实际字体大小,然后计算它以适合段落。
请参见此处的示例:http://jsfiddle.net/LNrgc/3/