gpt4 book ai didi

html - 将单词直接放在其他单词的下方或上方

转载 作者:太空狗 更新时间:2023-10-29 14:38:33 25 4
gpt4 key购买 nike

我希望在 div 标签中执行以下操作:

enter image description here

单词将使用 span 进行不同的着色。

我将在文本框中获得一些文本,通过 JavaScript,我需要动态更新到 div 以显示类似上面的内容。

最好的方法是什么?

它会涉及等宽字体吗?

它会涉及编写“隐藏”文本吗?

我希望以这种方式完成整个段落。

这可能看起来很奇怪,但我正在进行的研究要求我用多种颜色呈现给定文本中的某些词,我认为这可能是传达此信息的一种很好的方式。

更新文本框中的文本会更新以下变量,反过来我需要将这两个变量转换成如上图所示的内容。

text = "I am under the text above me and there is lots more text to come./n I am even moving onto a new line since I have more text"

color_per_word_position = {0:green, 1: red, 2: cyan, 4: yellow, 5: red, ...}

最佳答案

为此您必须使用等宽字体。*

我基本上看到两个选项: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

现在,间距需要手动处理。每个 span 都应该有一个 margin-left 将它推到所需的位置。但在我们这样做之前,我们需要知道一个字符的宽度(使用 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';

示例:http://jsfiddle.net/JC3Sc/

将它们放在一起

现在这里有一个基本的例子来说明它是如何工作的:

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) 我不想破坏所有的乐趣。但你明白了。

示例:http://jsfiddle.net/tNyqL/

关于html - 将单词直接放在其他单词的下方或上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18423625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com