2

我已经尝试了两种似乎不起作用的方法:1)我测量了单词的总数并将其除以 2,但是当单词很长并且并非所有单词的长度都相同时会出现问题,等等。 2)我测量了每个字符的高度(以像素为单位),整个正文的clientHeight,并将文本的总高度除以一个字符的高度,看看一列有多少行,另一列有多少行. 这种方法非常有效,除非需要考虑图像、段落和其他 HTML 标记。

我需要想出一种将图像和其他 HTML 标记考虑在内的新方法,而且我只能使用 HTML、CSS 和 JavaScript(没有 JQuery、JSON、Ajax 等)。如果您有想法/算法,请告诉我!谢谢 :)

4

1 回答 1

1

我在 JSFiddle http://jsfiddle.net/uWUBE/上为您创建了一个快速而肮脏的“hack”

希望它对您有所帮助,您可以将其编辑为更具动态性。这是一些代码。它基本上循环遍历单词的数量,然后将其添加到您分配给列的字符串中,我根本不是 Javascript 策划者,所以.. 可能有更好的方法。

`

//  Get the text
var txt = $("p").text();
//  Split every word
var words = txt.split(" ");
//  Count the amount of words
var amount = words.length
//  Amount of columns
var columnAmount = 2

//  Amount of words in first colum 
var firstColumn = Math.floor(amount / columnAmount);

//  String for first column
var firstColumnTxt = "";
//  String for second column
var secondColumnTxt = "";

//  loop trough the words and add them to the first column
for (var i = 0; i < firstColumn; i++){
    firstColumnTxt =     firstColumnTxt + " " + words[i]; 
}
//  loop trough the words and add them to the second column
for (var i = firstColumn; i < amount; i++){
    secondColumnTxt =   secondColumnTxt + " " + words[i];
}

// Add this to your first column
console.log(firstColumnTxt);
//  Add this to your second column
console.log(secondColumnTxt);

`

于 2013-01-14T11:14:10.393 回答