首页 > 解决方案 > IE11 默认 SVG 为 100% 宽度 - 如何重构此代码?

问题描述

我不知道添加width: 1em到 SVG 以解决 IE11 问题的替代方法(请参阅代码中的注释)。使用 codepen 中的代码。感谢任何帮助!谢谢 :)

https://codepen.io/ambrwlsn90/pen/zjZYpb

<div class="box">
    <span class="handle--draggable">
      <svg class="handle--icon" xmlns="http://www.w3.org/2000/svg" 
viewBox="0 0 10 32">
        <circle cx="2" cy="2" r="2" />
        <circle cx="8" cy="2" r="2" />
        <circle cx="2" cy="9" r="2" />
        <circle cx="8" cy="9" r="2" />
        <circle cx="2" cy="16" r="2" />
        <circle cx="8" cy="16" r="2" />
        <circle cx="2" cy="23" r="2" />
        <circle cx="8" cy="23" r="2" />
        <circle cx="2" cy="30" r="2" />
        <circle cx="8" cy="30" r="2" />
      </svg>
    </span>
</div>

.box {
  position: relative;
  width: 400px;
  height: 100px;
  border: 3px solid black;
  background-color: white;
  top: 50px;
  left: 100px;
  padding: 15px;
  line-height: 1.5em;
}

.handle--draggable {
  position: absolute;
  cursor: move;
  left: -26px;
  top: -3.5px;
}

/**
  * 1. Magic number added to fix visual bug in IE: 11
  */

.handle--icon {
  fill: black;
  background-color: grey;
  padding: 3.5px;
  height: 37px;
  width: 1em; /* 1. */
  position: relative;

  &:hover {
    left: -5px;
    border-right: 5px solid grey;
  }
}

标签: svgwidthinternet-explorer-11

解决方案


SVG 标签需要一些基本属性才能按预期呈现。如果您根据最外层的标签阅读W3C文档,您会找到答案:svg

对于嵌入的“svg”元素,放置“svg”元素的矩形区域的宽度。负值是错误(请参阅错误处理)。零值禁用元素的呈现。 如果未指定该属性,则效果如同指定了“100%”值。

因此,您需要指定 SVG 标记的widthheight属性,否则它将以 100% 的宽度呈现。

开始svg标签应如下所示:

<svg class="handle--icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 32" width=“10” height=“32”&gt;

然后 SVG 将看起来与跨浏览器相同。

在您的元素上定义了widthheight属性,svg您可以丢弃丑陋的 Internet Explorer 11 hack。


推荐阅读