在 JavaScript 中使用 HTML

问题描述 投票:0回答:1

我可以使用以下代码轻松地将文本添加到我的项目中:

const loadingText = $('#loading-text');
const text = "Your first sentence here"; // Your first sentence here

let i = 0;

const interval = setInterval(() => {
  if (i === text.length) {
    clearInterval(interval);
  } else {
    loadingText.text(loadingText.text() + text[i]);
    i++;
  }
}, 100); // Speed of animation (adjust as needed)
#loading-text {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin: 20px auto;
            width: 50%;
            opacity: 1;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="loading-text"></div>

现在我的问题是,有没有办法将这样的文本显示为没有标签的HTML(当然在文本上有标签效果)?

例如这样的事情:

const text = "lorem rerum <b style=\"color:#f00;\">aperiam</b> maxime reiciendis";

在上面的文本中,单词 (aperiam) 放置在标签之间,我还给它赋予了线性样式。

将上述行放入文本代码中,打印如下:

lorem rerum <b style="color:#f00;">aperiam</b> maxime reiciendis

有没有办法将输出显示为 HTML?

javascript html jquery
1个回答
0
投票

您无法一次添加 HTML 一个字符,因为您需要

不要使用单个字符串,而是将

text
制作为字符串数组,这样您就可以将标签包裹在每个字符周围以添加样式和颜色。

const loadingText = $('#loading-text');
const text = ["l", "o", "r", "e", "m", " ", "r", "e", "r", "u", "m", " ",
  '<b style="color:#f00;">a</b>', '<b style="color:#f00;">p</b>', '<b style="color:#f00;">e</b>', '<b style="color:#f00;">r</b>', '<b style="color:#f00;">i</b>', '<b style="color:#f00;">a</b>', '<b style="color:#f00;">m</b>',
  " ", "m", "a", "x", "i", "m", "e", " ", "r", "e", "i", "c", "i", "e", "n", "d", "i", "s"
];

let i = 0;

const interval = setInterval(() => {
  if (i === text.length) {
    clearInterval(interval);
  } else {
    loadingText.html(loadingText.html() + text[i]);
    i++;
  }
}, 100); // Speed of animation (adjust as needed)
#loading-text {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 20px auto;
  width: 50%;
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="loading-text"></div>

© www.soinside.com 2019 - 2024. All rights reserved.