【问题标题】:How to force HTML Elements keep a constant width to height ratio without JavaScript?如何在没有 JavaScript 的情况下强制 HTML 元素保持恒定的宽高比?
【发布时间】:2015-07-12 00:01:58
【问题描述】:

这是我使用 JavaScript 制作的示例。无论页面尺寸如何,每块积木的比例始终为 5:2,页面上始终有 20 块积木。

<!doctype html>
<html>
  <body>
    <svg id="wall" style="position:absolute;top:0;left:0;" width="100%" height="100%" onload="renderBackground();" onresize="renderBackground();">
    </svg>
    <script>
      var wall=document.getElementById("wall");
      function renderBackground()
      {
        var width=window.innerWidth;
        wall.innerHTML="";
        for(y=0;y<window.innerHeight;y+=width/25)
        {
          // Even Bricks
          for(x=0;x<width;x+=width/20)
          {
            createBrick(x,y,width/20,width/50);
          }
          // Odd Bricks
          for(x=0-width/40;x<width;x+=width/20)
          {
            createBrick(x,y+width/50,width/20,width/50);
          }
        }
      }
      function createBrick(x,y,width,height)
      {
        var brick=document.createElementNS(wall.namespaceURI,"rect");
        var shine=document.createElementNS(wall.namespaceURI,"rect");
        var drain=Math.random()*24;
        wall.appendChild(brick);
        wall.appendChild(shine);
        brick.setAttribute("x",x);
        brick.setAttribute("y",y);
        brick.setAttribute("width",width);
        brick.setAttribute("height",height);
        shine.setAttribute("x",x+width/20);
        shine.setAttribute("y",y+height/10);
        shine.setAttribute("width",9*width/10);
        shine.setAttribute("height",height/10);
        brick.setAttribute("style","fill:"+rgb(6*Math.random()+128-drain,12*Math.random()+128-drain,6*Math.random()+128-drain)+";stroke:"+rgb(51,51,68)+";stroke-width:"+String(height/20));
        shine.setAttribute("style","fill:"+rgb(160,160,160));
      }
      function rgb(r,g,b)
      {
        return "rgb("+String(Math.floor(Math.max(Math.min(r,256),0)))+","+String(Math.floor(Math.max(Math.min(g,256),0)))+","+String(Math.floor(Math.max(Math.min(b,256),0)))+")";
      }
    </script>
  </body>
</html>

如果我要使用 php 生成完全相同的页面,完全删除 JavaScript,我怎么能强制砖块保持相同的 5:2 比例而不需要调用 renderBackground() 来重绘和调整它们的大小每次调整窗口大小?

我想知道如何对所有元素执行此操作,而不仅仅是 SVG。

谢谢!

【问题讨论】:

  • 这和php有什么关系?
  • 我想用php重新创建这个页面,这样做很简单。不简单的是在调整页面大小时让砖块保持其设定的比例。

标签: javascript php html css svg


【解决方案1】:

如果您使用的是 IE9 或更高版本,除了少数移动浏览器之外,CSS 接受单位“视口宽度”(vw) 和/或“视口高度”(vh) 的尺寸。宽度为 5vw 且高度为 2vw 的元素将是视口 widthwidth 的 5% strong>,以及 height 中视口 width 的 2%。

由于您将元素的宽度和高度设置为仅视口宽度的百分比,因此它将保持恒定的纵横比。

问题:它在 SVG 元素中不起作用。它严格来说是一个 CSS 单元。它还考虑整个视口的宽度或高度,而不是任何包含元素。不过,您的示例占据了整个屏幕,所以没关系。

你会在知道要绘制多少行时遇到一些问题,至少在不使用 JavaScript 的情况下是这样。您将自己锁定为 20 列,但行完全取决于客户端的纵横比。

【讨论】:

  • 这正是我所需要的!最后,无论如何我只会绘制一定数量的行,因为砖块会在某个点褪色成黑色,并且页面永远不会短于该点。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 2012-03-09
  • 2013-09-07
  • 2012-07-14
  • 2016-02-29
相关资源
最近更新 更多