element.style.fontSize does not return size

element.style.fontSize does not return size

本文关键字:return size not does style fontSize element      更新时间:2023-09-26
我太失败了,

我准备遭受任何虐待,以找出为什么我不能做一些简单的事情,比如让 onload 函数告诉我正文字体大小是 20pt。 我读到眼睛流血,除了我之外,每个人似乎都能使下面的脚本起作用。

但是我的#@!/%#!代码吐出一个警告框,内容如下:(我使用了两行来确保这不是案例问题(

[  ]
[undefined]

实际上,我的目标是使用在头部部分或加载中执行的 scritp 来读取屏幕宽度,并通过公式设置正文字体大小。 [接下来的尝试是将正文标记排除在代码之外,并将脚本 document.write(( 放在带有设置正文字体大小的样式规范的正文标签中。 下面这应该只是一个热身运动。感谢任何和所有的帮助。

<html>
  <head>
    <style>
      body {font-size:20pt;color:white;font-weight:bold;background:grey;}
    </style>
    <script type="text/javascript">
      onload=function(){
        alert("[ " + document.getElementsByTagName("body")[0].style.fontSize +" ]"
           +"'n[ " + document.getElementsByTagName("body")[0].style.fontsize + " ]");
      }
    </script>
  </head>
  <body>
    <div>Test Text</div>
  </body>
</html>

以下是我在以下评论的帮助下获得

的。

它们都返回字体大小。

getComputedStyle(document.body).fontSize
getComputedStyle(document.body).getPropertyValue('font-size')

但是当用于设置字体大小时,它们会引发错误

getComputedStyle(document.body).fontSize = "30pt";
getComputedStyle(document.body).setProperty("fontSize", "25pt", "important") ;

另一方面,它们都设置了新的字体大小

document.body.style.fontSize = "200%";
document.getElementsByTagName("body")[0].style.fontSize = "400%";

但是当要求输入字体大小时,它们都返回长度为 0 的字符串。

document.body.style.fontSize 
document.getElementsByTagName("body")[0].style.fontSize 

这里有一个加载函数来确认它:

 onload=function(){
   var msg = "onload:'n";
   /* these both return font size.*/
   msg += "1. [ " + getComputedStyle(document.body).fontSize + "]'n";
   msg += "2. [ " + getComputedStyle(document.body).getPropertyValue('font-size') + "]'n";
   /* these both return a string of lenght 0.*/
   msg += "3. [ " + document.body.style.fontSize + "]'n"; 
   msg += "4. [ " + document.getElementsByTagName("body")[0].style.fontSize + "]'n"; 
     /*these both throw errors*/
     try { getComputedStyle(document.body).fontSize = "30pt";
   } catch (err) { msg += "5. [" + err.message + "]'n"; }
   try {getComputedStyle(document.body).setProperty("fontSize", "25pt", "important") ;
   } catch (err) { msg += "6. [" + err.message + "]'n"; }
   /*these both set new font size*/
   alert(msg);
   document.body.style.fontSize = "200%";
   setTimeout(function(){document.getElementsByTagName("body")[0].style.fontSize = "400%"},1500);
 }

显然我缺少一些东西,但现在这是有效的。圣诞快乐

  1. 您可以只使用document.body而不必使用 getElementsByTagName .

  2. fontsize是大写不当;这就是为什么您的第二个警报返回undefined

  3. 如果你想要CSS指定的元素的字体大小,你必须使用getComputedStyle

    alert(getComputedStyle(document.body).getPropertyValue('font-size'));
    // => "20pt"
    

    请参阅此处的 MDN 文档以获取getComputedStyle

Javascript 无法读取 CSS。你需要做的是内联定义你的字体大小,以便Javascript可以理解它。当您键入:

document.getElementsByTagName("body")[0].style.fontSize

它首先引用 DOM 中的元素。样式是该元素的属性,使用样式表样式时,样式的格式不同,而不是属性。所以你需要做的是:

<body style='font-size:20px'>
<!-- content -->
</body>