代码之家  ›  专栏  ›  技术社区  ›  Paul Draper

如何使用固定元素使svg响应?

  •  0
  • Paul Draper  · 技术社区  · 6 年前

    一些ui元素的大小是固定的;其他元素的大小是对容器大小的响应。

    例如,图的文本和图例通常是固定大小的,但其轴的大小通常是响应的。

    <svg font-size="14" height="200" width="100%" shape-rendering="crispEdges">
      <rect x="30" y="10" width="120" height="30" stroke="black" fill-opacity="0"></rect>
      <text color="black" x="32" y="24">Legend</text>
    </svg>

    <div style="font-size: 14px; height:200px; position:relative; width:100%">
      <div style="position:absolute; top:10px; left:30px; width: 116px; height: 26px; border: 1px solid black; padding: 2px">
        Legend
      </div>
      <div style="position:absolute; top:5px; left:5px; bottom: 5px; right:5px; border-left: 1px solid black; border-bottom: 1px solid black">
      </div>
    </div>

    据我所知,SVG不能这么做。我可以使用js并监听window resize事件,尽管这个事件并不总是被触发的,例如在打印时。

    浏览器svg中是否可以有固定的响应元素?

    1 回复  |  直到 6 年前
        1
  •  1
  •   hewiefreeman    6 年前

    我不想问你的问题,听一个调整大小的事件确实不会为打印做裁剪。因此,您需要做的是监听打印请求,并从中运行调整大小的代码:

    window.addEventListener("beforeprint", beforePrint);
    window.addEventListener("afterprint", afterPrint);
    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }
    
    function beforePrint() {
        //Resize for printing
    }
    
    function afterPrint() {
        //Resize again for after printing
    }
    

    这是从 this article .请仔细阅读它以获得更详细的描述、限制和其他可能的解决方案。

    对于需要调整大小但窗口调整大小事件不够的任何其他情况,通常至少有一个半简单的解决方法。javascript是您唯一的选择,它可以处理像在图中排序和调整项目大小这样复杂的事情。