SVG文本周围的矩形边框

chr*_*ina 8 css svg

试图在一些SVG文本周围加上边框,我的结果也各不相同.

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>
Run Code Online (Sandbox Code Playgroud)

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 */
}
Run Code Online (Sandbox Code Playgroud)

D3.js:

.on("click", function(d) {
    var selection = d3.select(this);
    selection.classed("mute", (selection.classed("mute") ? false : true));
 })
Run Code Online (Sandbox Code Playgroud)

这里我们X没有静音类灰色

这里我们有X静音类红色 但没有边界

这就是我们试图让边框看起来像 红色边框

注意:其父级是一个组,而不是HTML元素.

JS小提琴:http: //jsfiddle.net/chrisfrisina/yuRyr/5/

Rob*_*son 15

您发现SVG元素不支持CSS border属性.你的选择是

  1. <rect>在文本周围画一个红色作为边框
  2. <svg>如果外部元素的父元素是html元素,则在外部元素上添加边框.外部<svg>元素是替换元素,将支持CSS border属性.


Alv*_* K. 11

要在单击时围绕文本绘制矩形,请将代码更新为:

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");

})
Run Code Online (Sandbox Code Playgroud)

在这个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>
Run Code Online (Sandbox Code Playgroud)