脚本未从外部文件加载 css 属性

Script not loading css properties from external file

这是我的 2 个文件

HTML:

<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c=document.getElementById("myCanvas");
      alert(c.width)
    </script>

  </body>

</html>

CSS:

canvas {
  width:480;
  height:360;
  position:absolute;
  background-color:grey;
}

显然,我的 canvas 元素的宽度为 480,但由于某些原因,alert(c.width) returns 300。

这是因为 c.width 指的是元素的宽度属性。如果 canvas 元素中不存在该属性,您将获得它的默认值,即 300px。高度 (150px) 也会发生同样的情况。

要获得真正的 canvas 宽度,您可以使用 getBoundingClientRect()。另外,不要忘记在宽度和高度的 CSS 数值后添加 'px'。

canvas {
  width: 480px;
  height: 360px;
  position:absolute;
  background-color:grey;
}
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id=myCanvas></canvas>

    <script>
      var c = document.getElementById("myCanvas");
      alert(c.getBoundingClientRect().width)
    </script>

  </body>

</html>

尝试使用 c.offsetWidth 而不是 c.width。正如@BrunoSdoukos 在您尝试使用它的上下文中已经提到的 width 要求您将宽度设置为 <canvas> 元素的属性,如下所示:

<canvas id="myCanvas" width="480"></canvas>

因为 HTML 元素本身没有设置宽度属性,使用 c.width 将 return 默认宽度,即 300px。

因为您已经使用 CSS 指定了元素的宽度,以便在这种情况下获得元素宽度,您应该使用:

c.offsetWidth

这是 MDN 关于 HTMLElement.offsetWidth 的说法:

Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after.

您可以在这里 属性 了解更多信息:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth