首页 > 解决方案 > 为什么说我不能设置属性 fontSize 因为某些东西是未定义的?

问题描述

我最近参加了为期 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>

在训练营中,我们将此应用于图标而不是文本。该图标似乎悬停在其原始位置上方略大。我不想只是因为我的文本代码不起作用而复制粘贴图标代码。

标签: javascriptundefinedtypeerror

解决方案


您没有任何子元素,因此没有第一个子元素:

我做了一些小的编辑,这是一个工作片段。

  function thingHover() {
   var thing = document.getElementById('Thing');
   thing.firstElementChild.style.fontSize = '300%';
  }
  function thingNormal() {
  var thing = document.getElementById('Thing');
    thing.firstElementChild.style.fontSize = '100%';
  }
<script>

</script>
<div id='Thing'onmouseover="thingHover()" onmouseout="thingNormal()">
<p style='fontSize:100%;'>Dunno what I'm gonna do to this text yet, maybe add some JS?</p>
</div>


推荐阅读