根据视口高度缩放div

时间:2020-06-12 21:00:34

标签: html css iframe html5-video youtube-iframe-api

像视频元素一样缩放div。

我想像html5视频标签一样缩放div。

您可以在我的代码示例中看到,视频随着视口高度的变化而缩放:https://glitch.com/edit/#!/flawless-coconut-mole?path=index.html%3A17%3A99

我想要相同的效果,但要有一个div。该div内将包含一个iframe(Youtube iframe)。我可以使iframe保持16:9的宽高比,但无法使其容器更改其高度并因此缩放其子级。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

首先,您的script标记应位于head标记中或紧随body标记之后,最好的方法是在逻辑标记之后紧跟您编写JavaScript您的身体标签(以加快网页的加载速度)。 像这样:

您可以使用div包装iframe代码: PS:您需要删除默认的高度和宽度属性

<div class="embed">
  <iframe src="https://www.youtube.com/embed/4VIy9lF_EHg" allowfullscreen </iframe>
</div>

并像这样使用CSS

<style>
    .embed {
      overflow: hidden;
      padding-top: 56.25%;
      position: relative;
    }

    .embed iframe {
       height: 100%;
       width: 100%;
       position: absolute;
       left: 0;
       top: 0;
    }
</style>

对于最终结果:

.embed {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.embed iframe {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Hello!</title>

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css">

    <!-- import the webpage's javascript file -->
  </head>  
  <body>
<div class="embed">
  <iframe src="https://www.youtube.com/embed/4VIy9lF_EHg" allowfullscreen></iframe>
</div>

  </body>
  <script src="/script.js"></script>
  <script src="https://button.glitch.me/button.js" defer></script>
</html>

答案 1 :(得分:0)

您可以在CSS中使用vh单元。这是一个例子。

var sizeElement = document.getElementById('window-size');
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight
sizeElement.innerText = `Window size: ${windowWidth} x ${windowHeight}`;
var iframeElement = document.getElementById('iframe-size');
var iframe = document.getElementsByTagName('iframe')[0];
var iframeWidth = iframe.clientWidth;
var iframeHeight = iframe.clientHeight;
iframeElement.innerText = `iframe size: ${iframeWidth} x ${iframeHeight}`;
var totalSizeElement = document.getElementById('total-size');
totalSizeElement.innerText = `iframe width is ${Math.round(iframeWidth * 100 / windowWidth)}% of window width. iframe height is ${Math.round(iframeHeight * 100 / windowHeight)}% of window height.`;
.container {
  background-color: gray;
  /* Makes sure the iframe is visible */
  height: 9vh;
  width: 16vh;
  /* Maintain aspect ratio */
}

iframe {
  /* iframe takes up entire container */
  width: 100%;
  height: 100%;
}
<div class="container">
    <iframe></iframe>
<div>
<p id="window-size"></p>
<p id="iframe-size"></p>
<p id="total-size"></p>

如果您单击“整页”并调整浏览器的大小,则<iframe>的大小将成比例。

vhvw分别是分别对应于视口高度和宽度的单位。 1 vh等于视口高度的1/100。您可以使用max-widthmin-width以及它们的相应高度来限制<iframe>可以得到的大小。

相关问题