为什么说我无法设置属性 fontSize 因为某些内容未定义?

问题描述 投票:0回答:3

我最近参加了为期 5 天的训练营,并在开始完整课程之前尝试自学更多内容。我正在尝试使用与训练营中使用的相同的“鼠标悬停”功能来增加 fontSize,但它说它无法设置 undifined 的属性 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>

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

javascript undefined typeerror
3个回答
0
投票

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

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

  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>


0
投票

以下代码中有拼写错误,调用时添加函数括号

function thingHover() {
           document.getElementById('Thing').style.fontSize='300%'; //remove firstChild
         }
         function thingNormal() {
           document.getElementById('Thing').style.fontSize='100%'; //remove firstChild
         }
           </script>
<p id='Thing' onmouseover="thingHover()" onmouseout="thingNormal()"> Dunno what I'm gonna do to this text yet, maybe add some JS? </p> <!--add  space between two attributes and add () on onmouseout-->


0
投票

    function thingHover() {
        let hov = document.getElementById('Thing');
        hov.style.fontSize = '300%';
    }

    function thingNormal() {
        let normal = document.getElementById('Thing');
        normal.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>

© www.soinside.com 2019 - 2024. All rights reserved.