【发布时间】:2019-11-27 08:17:56
【问题描述】:
我最近参加了为期 5 天的训练营,并在开始完整课程之前尝试自学更多。我正在尝试使用与我在训练营中使用的相同的“鼠标悬停”功能来增加 fontSize,但它说它无法设置未定义的属性 fontSize。我相信我设置了我想要更改的 Id 并指定了我想要更改多少...
老实说,我对此很陌生,只是想克服我的第一个 Javascript 障碍。
function thingHover() {
document.getElementById('Thing').firstChild.style.fontSize = '300%';
}
function thingNormal() {
document.getElementById('Thing').firstChild.style.fontSize = '100%';
}
<p id='Thing' onmouseover="thingHover()" onmouseout="thingNormal"> Dunno what I'm gonna do to this text yet, maybe add some JS? </p>
在训练营中,我们将此应用于图标而不是文本。该图标似乎悬停在其原始位置上方略大。我不想只是因为我的文本代码不起作用而复制粘贴图标代码。
【问题讨论】:
-
getElementById返回单个元素并且p标签没有任何子元素,因此firstChild返回undefined -
你对比过图标码和你的文字码的区别吗?
-
每当你遇到像
cannot set property B because A is undefined这样的错误时,你的代码就会在某处出现A.B,而A是未定义的。在这种情况下,您使用.firstChild来获取文本节点,并使用.style来获取样式,但这会产生undefined,因为文本节点没有样式属性。 -
另外,如果你参加了一个教授使用内联事件侦听器属性的编码训练营和
firstElementChild.firstElementChild,你可能应该要求退款。 -
还应该注意
#Thing:hover { font-size: 300% }做同样的事情。
标签: javascript undefined typeerror