首页 > 解决方案 > 为什么我不能对这个元素应用任何东西?

问题描述

所以我正在为魔方做秒表。我有一个div元素(记录)应该显示单击按钮时我想输入的时间,但是我不能将p元素附加到 this div,也不能对其应用任何 CSS。

在 rubik.js 中:

document.getElementById("records").appendChild(document.createElement("p").appendChild(document.createTextNode(`${formula.first}.${formula.second}.${formula.third}`)));

当我在其中附加一个子段落时,div它就变成了一个text元素。CSS中的div元素:

#records {
    position: absolute;
    bottom: 0;
    right: 0;
    width: calc(100% - 620px);
    height: 130px;
    border-top: 2px solid black;
    background-color: white !important;
    overflow-y: scroll;
}

这两个按钮(添加当前时间删除上次时间按钮)有position一个fixed

谢谢你的时间。

标签: javascripthtmlcssdom

解决方案


Node.appendChild()方法返回附加的节点或文本节点。所以这个document.createElement("p").appendChild(document.createTextNode(${formula.first}.${formula.second}.${formula.third}))返回附加文本节点,而不是p元素。

创建p元素,将其分配给变量,然后附加文本节点,并将p元素附加到#records

const formula = { first: '1', second: '2', third: '3' };

const p = document.createElement("p")

p.appendChild(document.createTextNode(`${formula.first}.${formula.second}.${formula.third}`))

document.getElementById("records").appendChild(p);
<div id="records"></div>


推荐阅读