【问题标题】:Unable to set max-width of SVG text无法设置 SVG 文本的最大宽度
【发布时间】:2018-11-11 05:32:42
【问题描述】:

我有一个非常简单的页面和任务,但令我沮丧的是,我无法让我的文字与正确的max-width 相匹配。我看过:read width of d3 text elementWhats the CSS to make something go to the next line in the page?,等等,但我还是想不通。

svg 文本没有很好地流到下一行,而是在页面上蔓延,直到超出范围。这是我的css和代码

var svg = d3.select('body').append('svg')
    .attr('width', 300)
    .attr('height', 200);

var textG = svg.append('g');

textG.append('text')
    .attr('x', 20)
    .attr('y', 30)
    .attr('class', 'myText')
    .text('This line should be about three to four lines long, but because I am so stupid I cannot make it do what I want it to do. Woe is me.');
.myText {
    font-size: 1.3em;
    fill: gray;
    width:10%;
    max-width:10%;
    display:block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="//d3js.org/d3.v3.min.js"></script>
</head>
<body>

问题:我可以从 CSS 方面或 JS 方面做些什么来使我的 svg 文本采用最大宽度样式规则?我希望它转到下一行,而不是在第一行的范围内无限前进。

【问题讨论】:

  • SVG 不通过 CSS 支持这一点。您必须手动将文本拆分为 tspan 元素或使用 foreignObject 和 html 来包装文本。

标签: css d3.js svg


【解决方案1】:

您可以做的是将字符串分成三或四部分,然后在&lt;text&gt; 元素中使用多个&lt;tspan&gt; 元素,而不是将整个文本插入&lt;text&gt;

另一种解决方案是使用&lt;foreignObject&gt;

这是一个小提琴:

var svg = d3.select('body').append('svg')
  .attr('width', 350)
  .attr('height', 500);

var textG = svg.append('g');

var fullTxt = 'This line should be about three to four^lines long, but because I am still^learning stuff, I cannot make it do^what I want it to do. Woe is me.'

var b = fullTxt.split('^');

textG.append('text')
  .attr('x', 20)
  .attr('y', 30)
  .attr('class', 'myText')
  .selectAll('tspan').data(b)
  .enter().append('tspan')
  .text(function(d) {
    return d;
  })
  .attr("textLength", 250)
  .attr("lengthAdjust", "spacingAndGlyphs")
  .attr('dy', '1em').attr('x', '15');
.myText {
  font-size: 1.3em;
  fill: gray;
  width: 10%;
  max-width: 10%;
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <script src="//d3js.org/d3.v3.min.js"></script>
</head>

<body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2013-02-09
    • 2015-06-19
    • 2014-06-26
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多