代码之家  ›  专栏  ›  技术社区  ›  Brian Anderson

“resize”窗口事件似乎只在垂直调整时触发

  •  1
  • Brian Anderson  · 技术社区  · 6 年前

    我试图根据以下规则调整框的宽度和高度:

    1. 每当调整窗口大小时,都需要重新计算框的大小
    2. 框必须是主体的高度,有最小的边距,但没有滚动条
    3. 我只能使用HTML5、CSS3和vanilla JS(没有jQuery)

    我想我有一个很好的工作模式,除了一点小麻烦外,还可以。水平调整浏览器大小仅在开始时触发一次resizeWindow()。一旦触发第一个水平大小调整,水平大小调整的次数都不会触发对框文本的更新。在垂直方向调整窗口大小会导致所需的行为。

    我希望看到文本更新(通过resizeWindow()调用),即使框的大小不必更改。

    代码段似乎只能在整页模式下工作:/

    function resizeWindow() {
      ht = window.innerHeight;
      wd = window.innerWidth;
      elPreview = document.getElementById("preview");
      elPreview.style.height = "98.5vh";
      elPreview.style.width = (ht / 2) + "px";
      elPreviewText = document.querySelector("#preview p");
      elPreviewText.textContent = "Width: " + (ht / 2) + ", Height: " + ht;
    }
    
    window.addEventListener('resize', resizeWindow, true);
    html, body {
      height: 100%;
      width: 100%;
      margin: 0;
    }
    
    .box {
      background-color: black;
      border-radius: 20px;
      color: white;
      padding: 5px 0;
      font-size: 1em;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="index_proto.css">
    </head>
    <body>
      <div class="box" id="preview">
        <p>Preview</p>
      </div>
      <script src="index_proto.js"></script>
    </body>
    </html>
    2 回复  |  直到 6 年前
        1
  •  1
  •   Tom Edwards    6 年前

    你可以一直使用css @media 更改元素的宽度和高度。

    @media only screen and (max-width: 720px) {
        .DivElementClassName {
            width: 300px;
            margin-left:25%;
        }
    }
    
        2
  •  0
  •   Brian Anderson    6 年前

    function resizeWindow() {
      ht = window.innerHeight;
      wd = window.innerWidth;
      elPreview = document.getElementById("preview");
      elPreview.style.height = "98.5vh";
      elPreview.style.width = (ht / 2) + "px";
      elPreviewText = document.querySelector("#preview p");
      elPreviewText.textContent = "Width: " + wd + ", Height: " + ht;
    }
    
    window.addEventListener('resize', resizeWindow, true);
    html, body {
      height: 100%;
      width: 100%;
      margin: 0;
    }
    
    .box {
      background-color: black;
      border-radius: 20px;
      color: white;
      padding: 5px 0;
      font-size: 1em;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="index_proto.css">
    </head>
    <body>
      <div class="box" id="preview">
        <p>Preview</p>
      </div>
      <script src="index_proto.js"></script>
    </body>
    </html>

    正如我上面说的,请不要理会。一个程序员(我)把一个永远不会改变的数字输入一个他期望改变的输出。