返回

html-通过 JavaScript 用字符串填充 <code>

发布时间:2022-07-20 07:34:23 189
# css

我正在尝试用 JavaScript 字符串填充 HTML <code> 标记。这会弄乱格式并使整个代码出现在可滚动的单行中。当我直接在 HTML 中填充 < code > 标记时,会显示正确的换行符。

我正在使用 hljs 突出显示代码中的关键词

function addNewCodeObject() {
let n = document.createElement("div")
let p = document.createElement("p")
let pre = document.createElement("pre")
let code = document.createElement("code")

n.classList.add("code-container")
p.classList.add("code-content")

    code.innerText = "public class SwapNumbers {\n" +
    "\n" +
    "    public static void main(String[] args) {\n" +
    "\n" +
    "        float first = 1.20f, second = 2.45f;\n" +
    "\n" +
    "        System.out.println(\"--Before swap--\");\n" +
    "        System.out.println(\"First number = \" + first);\n" +
    "        System.out.println(\"Second number = \" + second);\n" +
    "\n" +
    "        // Value of first is assigned to temporary\n" +
    "        float temporary = first;\n" +
    "\n" +
    "        // Value of second is assigned to first\n" +
    "        first = second;\n" +
    "\n" +
    "        // Value of temporary (which contains the initial value of first) is assigned to second\n" +
    "        second = temporary;\n" +
    "\n" +
    "        System.out.println(\"--After swap--\");\n" +
    "        System.out.println(\"First number = \" + first);\n" +
    "        System.out.println(\"Second number = \" + second);\n" +
    "    }\n" +
    "}"

pre.appendChild(code)
p.appendChild(pre)
n.appendChild(p)


document.getElementById("entire-thing").append(n)
hljs.highlightAll()

}

这使代码显示在一行中

<div class="code-container" id="cont">

    <p class="code-content">
        <pre>
            <code id="mycode">
public class SwapNumbers {

    public static void main(String[] args) {

        float first = 1.20f, second = 2.45f;

        System.out.println("--Before swap--");
        System.out.println("First number = " + first);
        System.out.println("Second number = " + second);

        // Value of first is assigned to temporary
        float temporary = first;

        // Value of second is assigned to first
        first = second;

        // Value of temporary (which contains the initial value of first) is assigned to second
        second = temporary;

        System.out.println("--After swap--");
        System.out.println("First number = " + first);
        System.out.println("Second number = " + second);
    }

这可以按预期工作,但它显然只是HTML,没有使用JS,我已经尝试用
但这行不通

谢谢你的建议

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像