javascript - 将 SVG 元素的宽度和高度设置为 100% 对我们有什么好处吗?

标签 javascript html css angular svg

Angular Material 文档应用程序有一个 SVG 查看器可以执行此操作:

  inlineSvgContent(template) {
    this.elementRef.nativeElement.innerHTML = template;

    if (this.scaleToContainer) {
      let svg = this.elementRef.nativeElement.querySelector('svg');
      svg.setAttribute('width', '100%');
      svg.setAttribute('height', '100%');
      svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
    }
  }

IIUC 要使 SVG 缩放到容器,我们需要做的就是使用正确的 viewBox 参数保存它 as explained here .

这是回答的演示圈:

  <svg viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="gold"/>
    <rect x="10" y="50" width="20" height="50" fill="gold"/>
    <rect x="70" y="50" width="20" height="50" fill="gold"/>
    <circle cx="35" cy="45" r="5"/>
    <circle cx="65" cy="45" r="5"/>
  </svg>

该圆将适合任何容器,无需设置 width=100%height=100%

那么我假设 Angular 团队这样做的原因是因为想要将 widthheight 设置为另一个用例的某个固定值?

一般来说,我只是对设计以及我们是否从中获益感到好奇。换句话说,这是 UX 开发人员的常见模式吗?为什么?

最佳答案

在这种情况下,它可能会有用,因为似乎此方法不知道如何声明 svg 元素,因此它们将覆盖这些属性,以便之前设置的任何内容都不会阻止元素的响应.

由于此函数名为 inlineSvgContent,我们可以假设它是一种 sanitizer 。

使独立的 svg 图像具有绝对宽度和高度属性(例如以 px 为单位)是很常见的(甚至被推荐),以便渲染器知道如何绘制它。如果不这样做,默认值为 100%,但在某些情况下,很难理解 100% 的确切含义。具有绝对宽度和高度允许众所周知的纵横比。


现在,如果您要从头开始创建元素,那将毫无用处,因为这些实际上是默认值:

const svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );

console.log( 'width', svg.width.baseVal.valueAsString ); // 100%
console.log( 'height', svg.height.baseVal.valueAsString ); // 100%
console.log( 'preserveAspectRatio', svg.preserveAspectRatio.baseVal );
// align: 6 => SVG_PRESERVEASPECTRATIO_XMIDYMID
// meetOrSlice: 1 => SVG_MEETORSLICE_MEET
// => "xMidYMid meet"

关于javascript - 将 SVG 元素的宽度和高度设置为 100% 对我们有什么好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330689/

相关文章:

javascript - 在 angular-js 应用程序中使用 Google 跟踪代码管理器 'click-listener' 时,“无法对数据层进行字符串化”

jquery - 将关闭图标添加到固定到特定位置的模态弹出窗口

html - IE6 忽略事件链接 CSS 样式

HTML 不适合有空间的文本

javascript - 如何在打印布局 html 中设置 img 样式

javascript - 拖动元素时平移 Svg

javascript - 返回&: How to send signup page with different role to two kinds of users

javascript - NodeJS - 导出多个函数

css - 字体在 font-awesome 4.7 版本中停止工作

jquery - Bootstrap 3 : columns float right when resized