我有一个非常简单的页面和任务,但令我沮丧的是,我无法让我的文本采用正确的 max-width
。我看过: read width of d3 text element 、 Whats 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 文本采用最大宽度样式规则?我希望它转到下一行,而不是在第一行的范围内无限前进。
最佳答案
你可以做的是将你的字符串分成三个或四个部分,然后使用多个 <tspan>
<text>
中的元素元素而不是将整个文本插入 <text>
.
另一种解决方案是使用 <foreignObject>
.
这是一个 fiddle :
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>
关于css - 无法设置 SVG 文本的最大宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637246/