首页 > 解决方案 > 为什么 video.width 是 0 但实际上是 539?

问题描述

这是一张图片

并且宽度和高度不是0,但是当我在控制台中打印它时,它返回0。

这是我如何打印它的代码:

const video = document.getElementById("remoteVideo");
video.addEventListener('play', () => {
      setInterval(async () => {
      console.log(video.width);
      console.log(video.height);
      }, 100)
    });

这是完整的html:

<!DOCTYPE html>
<html lang="en"></html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
      html { height: 100%; }
      body { height: 100%; margin: 0; background: #111; text-align: center; }
      #remoteVideo { height: 70%; margin-top: 5%; background: #000; }
      #localVideo { width: 20%; position: absolute; right: 1.1em; bottom: 1em; border: 1px solid #333; background: #000; }
      #callButton { position: absolute; display: none; left: 50%; font-size: 2em; bottom: 5%; border-radius: 1em; }
  </style>
  <script defer src="static/face-api.min.js"></script>

</head>
<body>

    <video id="localVideo" autoplay muted></video>
    <video id="remoteVideo" autoplay></video>
    <button id="callButton" onclick="createOffer()">✆&lt;/button>

    <script src="/socket.io/socket.io.js"></script>
    <script defer src="static/script.js"></script>
</body>
</html>

我究竟做错了什么?

标签: javascripthtml

解决方案


您可以使用

没有异步的getBoundingClientRect

以下是您如何使用https://www.pexels.com/videos/在一个最小的、可重现的示例中发布您的问题

const video = document.getElementById("remoteVideo");
video.addEventListener('play', () => {
    console.log(video.getBoundingClientRect() );
});
html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
  background: yellow;
  text-align: center;
}

#remoteVideo {
  height: 70%;
  margin-top: 5%;
  background: red;
}

#localVideo {
  width: 20%;
  position: absolute;
  right: 1.1em;
  bottom: 1em;
  border: 1px solid #333;
  background: pink;
}

#callButton {
  position: absolute;
  display: none;
  left: 50%;
  font-size: 2em;
  bottom: 5%;
  border-radius: 1em;
}
<video id="localVideo" src="https://player.vimeo.com/external/357005099.sd.mp4?s=a95b2118e2fa52097ad9933b56d50ebcc9f2f1c9&profile_id=139&oauth2_token_id=57447761" autoplay muted>Video</video>
<video id="remoteVideo" autoplay src="https://player.vimeo.com/external/340284081.sd.mp4?s=00350f6e127d8ac3777d74528fa439944f7d9f2c&profile_id=139&oauth2_token_id=57447761">Video</video>
<button id="callButton" onclick="createOffer()">Button ✆&lt;/button>


推荐阅读