您可以获取每列的根元素以及该元素的根innerText
元素。
var elements = document.getElementById("container").getElementsByTagName("p");
for(var i = 0; i < elements.length; ++i) {
console.log("COLUMN " + i + "\n");
console.log(elements[i].innerText);
};
小提琴:http: //jsfiddle.net/4mHCb/3/
您可以打开浏览器的 JS 控制台并查看输出(chrome 中的 ctrl+shift+j)。
编辑
感谢 voithos 指出我忽略的内容。考虑到他所说的话,我很确定没有办法准确地做到这一点。但是,这是一个与您正在寻找的近似的总黑客。它使用屏幕外画布和 2d 上下文的mesaureText方法:http:
//jsfiddle.net/4mHCb/5/
var elements = document.getElementById("container").getElementsByTagName("p");
var g2d = document.createElement("canvas").getContext("2d");
var containerStyle = document.getElementById("container").style;
var columnWidth = 150;
var lineHeight = 18;
var columnHeight = 300;
var linesPerCol = columnHeight / lineHeight;
var results = [];
for(var i = 0; i < elements.length; ++i) {
var colText = elements[i].innerText;
var textWidth = g2d.measureText(colText).width;
var numCols = textWidth / (columnWidth * linesPerCol);
var charIdx = 0;
for (var column = 0; column < numCols; ++column) {
var currString = "";
var currTextWidth = 0;
for (; charIdx < colText.length && currTextWidth < columnWidth*linesPerCol; ++charIdx) {
currString += colText[charIdx];
currTextWidth = g2d.measureText(currString).width;
}
results.push(currString);
}
}
for(var column = 0; column < results.length; ++column) {
console.log("COLUMN: " + column);
console.log(results[column]);
}
</p>