创建<p>元素并在同一个函数中更改样式

时间:2016-02-01 02:16:55

标签: javascript css css-animations appendchild

希望你们过得愉快。

我正在使用&#34; createElement&#34;和&#34; appendChild&#34;在div中创建一个段落。

代码看起来像这样(抱歉粗略的工作):

var para = document.createElement("p");
para.id = "cursorText";
var node = document.createTextNode(rand);
para.appendChild(node);
var element = document.getElementById("cursorPos");
element.appendChild(para);

这会创建段落并在其中放置一个随机单词,并将其附加到div&#34; cursorPos&#34;。

它会创建如下所示的元素:

<p id="cursorText">Hello StackOverflow</p>

每次单击按钮(对于数组中的随机单词),id para中的文本都会更改,目标是在每次单击后淡出。

我尝试使用以下代码执行此操作:

var elem = document.getElementById("cursorText");
elem.style.transition = "opacity 2.0s linear 1s";
elem.style.opacity = "0";

但它一直告诉我&#34;未捕获的TypeError:无法读取属性&#39; style&#39; of null&#34; @ Line 40 AKA启动elem.style.transition的行...

请注意以下几点:2个属性(创建文本节点和动画)必须在同一个函数中。我已经在一个单独的功能中尝试过它并且它不起作用。

感谢阅读这个神秘的混乱,任何帮助都非常感激:)

2 个答案:

答案 0 :(得分:2)

您将ID设置为&#34; cursorText&#34;,而不是&#34; para&#34;。

另外,我个人建议您创建一个CSS类,并在新对象上设置class属性,以使该CSS类与您要对新创建的段落进行的所有更改相匹配。

答案 1 :(得分:0)

当你创建变量elem时,你被告知要通过id从未初始化。如果你看看你的para class,你会注意到你输出的id是 ID =&#34; cursorText&#34; 虽然当你试图风格化时,你告诉它要抢 ID =&#34;第&#34 ;. 因此,您收到null ....快速修复将只是更改您的ID查询功能。即

  

var elem = document.getElementById(&#34; cursorText&#34;);