CSS SVG 文本周围的矩形边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17218108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rectangle border around SVG text
提问by chris Frisina
Trying to put a border around some SVG text, and I am getting varying results.
试图在一些 SVG 文本周围放置边框,但我得到了不同的结果。
HTML: (with the mute class)
HTML:(使用静音类)
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<text x="37.5" y="37.5" class="ablate-x mute">X</text>
</svg>
CSS:
CSS:
.ablate-x {
font-size: 24px;
color: gray;
opacity: 0.5;
font-weight: 900;
cursor: hand;
cursor: pointer;
}
.mute {
opacity: 1;
fill: red;
stroke: red;
stroke-width: 2px;
/* we tried border: 2px solid red; but it didn't work */
}
D3.js:
D3.js:
.on("click", function(d) {
var selection = d3.select(this);
selection.classed("mute", (selection.classed("mute") ? false : true));
})
Here we have the X
without the mute class
这里我们有X
没有静音类
Here we have the X
with the mute class but without the border
这里我们有X
静音类但没有边框
This is what we are trying to get the border to look like
这就是我们试图让边界看起来像的
Note: its parent is a group, not an HTML element.
注意:它的父元素是一个组,而不是一个 HTML 元素。
JS Fiddle: http://jsfiddle.net/chrisfrisina/yuRyr/5/
回答by Robert Longson
SVG elements don't support the CSS border property as you have discovered. Your options are
正如您所发现的,SVG 元素不支持 CSS 边框属性。您的选择是
- Draw a red
<rect>
around the text as a border - Put a border on the outer
<svg>
element if its parent is a html element. The outer<svg>
element is a replaced element and will support the CSS border property.
<rect>
在文本周围画一个红色作为边框<svg>
如果其父元素是 html 元素,则在外部元素上放置边框。外部<svg>
元素是一个替换元素,将支持 CSS 边框属性。
回答by Alvin K.
To draw a rect around text on click, update the code to:
要在单击时围绕文本绘制矩形,请将代码更新为:
var svgcanvas = d3.select('svg');
$("#xc").on("click", function (d) {
var selection = d3.select(this);
var rect = this.getBBox();
var offset = 2; // enlarge rect box 2 px on left & right side
selection.classed("mute", (selection.classed("mute") ? false : true));
pathinfo = [
{x: rect.x-offset, y: rect.y },
{x: rect.x+offset + rect.width, y: rect.y},
{x: rect.x+offset + rect.width, y: rect.y + rect.height },
{x: rect.x-offset, y: rect.y + rect.height},
{x: rect.x-offset, y: rect.y },
];
// Specify the function for generating path data
var d3line = d3.svg.line()
.x(function(d){return d.x;})
.y(function(d){return d.y;})
.interpolate("linear");
// Draw the line
svgcanvas.append("svg:path")
.attr("d", d3line(pathinfo))
.style("stroke-width", 1)
.style("stroke", "red")
.style("fill", "none");
})
On this html:
在这个 html 上:
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<svg width="720" height="720">
<text x="37.5" y="37.5" id="xc">X</text>
</svg>
</body>
</html>