【问题标题】:Why my code doesn't work when the script tag is in the head tag? [duplicate]当脚本标签在头标签中时,为什么我的代码不起作用? [复制]
【发布时间】:2022-01-05 11:59:17
【问题描述】:

我正在制作一个带有视频的网页。 我想根据窗口的大小来改变视频的大小。

下面的代码是我的 HTML 代码:

<video id="video" controls="controls" poster="images/video_poster.png" width="320" height="240">
      <source src="video/Minions.mp4" type="video/mp4">
      <source src="video/Minions.ogv" type="video/ogg">
</video>

我的脚本代码如下:

  <script>var video = document.getElementById("video");
    function changeVideoSize() {
      console.log("width is: ", window.innerWidth)
      if (window.innerWidth > 900) {
        video.width = "640";
        video.height = "480";
      }
      else {
        video.width = "320";
        video.height = "240";
      }
    }
    window.addEventListener("resize", changeVideoSize)
    function init() {
    }
    init();
  </script>

首先,我把这段脚本代码放在了head标签的最后,结果报错“Cannot set properties of null (setting 'width')”。

我被这个错误困扰了一个小时...... 然后经过多次不同的尝试, 我把它放在body标签的末尾,它起作用了。

为什么会这样? 将它放在头部和身体之间的主要区别是什么? 我应该总是将脚本标签放在正文标签的末尾吗? 还是视情况而定?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    那是因为纯序列。在这种情况下,解释器从上到下读取。如果你的代码在头上说给我元素 X 并且它还没有在 DOM 中,那么那是空的。在页脚中有所不同,元素 x 已经加载到 DOM 中,这就是脚本起作用的原因。 JS 在大多数情况下总是在结束 body 标记之前。

    【讨论】:

      【解决方案2】:

      基本上当你把它放在你的 head 标签中时,脚本会在 body 标签之前解析。所以文档中没有带有 id video 的视频标签。 使用具有 defer 属性的外部脚本或将脚本放在标签内的 html 代码下方。 对不起我的英语不好。

      【讨论】:

        【解决方案3】:

        首先,HTML 是从 top to bottom 中解析出来的,所以无论先遇到什么都会运行。

        如果您将script 标签放在head 标签的末尾,那么它将在HTML body 之前首先运行,因此您无法设置width,因为当您使用时

        document.getElementById("video")
        

        它将返回null,因此您无法在null 上设置属性。因为在此声明时该元素不存在。

        <html>
        
        <head>
          <script>
            const heading = document.querySelector("h1");
            console.log(heading); // null
          </script>
        </head>
        
        <body>
          <h1> This is heading</h1>
        </body>
        
        </html>

        所以你必须把script标签放在body标签的末尾。这样当 JS 被解析并被执行时,它就可以找到HTML 元素并执行语句。

        <html>
        
        <head>
        </head>
        
        <body>
          <h1> This is heading</h1>
          
            <script>
            const heading = document.querySelector("h1");
            console.log(heading); // h1 element
          </script>
        </body>
        
        </html>

        【讨论】:

          猜你喜欢
          • 2013-02-09
          • 2014-10-09
          • 2022-12-05
          • 2020-04-09
          • 2021-10-27
          • 2022-01-14
          • 1970-01-01
          • 2017-10-23
          • 1970-01-01
          相关资源
          最近更新 更多