你必须使用等宽字体.*
我基本上看到两个选项:1.使用空格2.边距.
选项1
你的文字看起来像
I•am•under•the•text•above
••am•under•••••text•above
其中•表示空格字符.在CSS方面非常简单,因为您不必担心间距.浏览器为您完成所有操作.示例:http://jsfiddle.net/PYXdr/
*好吧,有可能使用任何字体,使用大量的JS,但我想这不值得.
选项2
由于您可能不希望在跨度之间使用空格,因此您可能更喜欢这样:
I•am•under•the•text•above
am•under text•above
现在,需要手动处理间距.每个跨度应该得到一个左边距,将其推到所需的位置.但在我们能够做到这一点之前,我们需要知道一个字符的宽度(使用JS,因为CSS没有提供).好的,非常简单:
var el = document.createElement('pre');
el.style.display = 'inline-block';
el.innerHTML = ' ';
document.body.appendChild(el);
var width = parseFloat(getComputedStyle(el).width);
document.body.removeChild(el);
现在让我们继续前进并移动跨度:
span1.style.marginLeft = (2 * width) + 'px';
span2.style.marginLeft = (5 * width) + 'px';
把它们放在一起
现在,这是一个如何工作的基本示例:
var text = "I am under the text above me and there is lots more text to come.\nI am even moving onto a new line since I have more text"
var highlightBorders = [[2,3,4,6],[6,7]]; // YOUR TASK: implement the logic to display the following lines
var color_per_word_position = {0:'lime',1: 'red',2: 'cyan',3:'orange',4: 'yellow',5: 'red'}
/* generate CSS */
var style = document.createElement('style');
for (var i in color_per_word_position) {
style.innerHTML += '.hl' + i + '{background:' + color_per_word_position[i] + '}';
}
document.head.appendChild(style);
/* generating the text */
text = text.split('\n');
var pre = document.createElement('pre');
text.forEach(function (line,i) {
var div = document.createElement('div');
var words = line.split(' ');
var result = [];
highlightBorders[i].forEach(function (len,j) {
var span = document.createElement('span');
span.innerHTML = words.splice(0,len).join(' ');
span.className = 'hl' + j;
if (j) {
span.style.marginLeft = width + 'px' // YOUR TASK: implement the logic
}
div.appendChild(span);
});
pre.appendChild(div);
});
document.body.appendChild(pre);
这不是一个完整的解决方案,因为a)我真的没有看到你要突出的部分和b)我不想破坏所有的乐趣.但是你明白了.