【问题标题】:how to set the exact width in svg如何在svg中设置确切的宽度
【发布时间】:2015-05-22 19:00:58
【问题描述】:

如果我将鼠标悬停在矩形上,边框大小会超出矩形大小。我知道,因为父节点宽度是100,这就是显示矩形边框的原因。

如果我将父节点宽度设置为40,它可以正常工作,但我需要相同的行为而不更改父节点的widthstroke-width

我怎样才能做到这一点?

// In mouse hover, I have set the style:
var links = $('#ch');
links.hover(function() {
  $('#ch').attr('class', 'st');
}, function() { //mouseout
  $('#ch').attr('class', '');
});
.st {
  stroke-width: 60px;
  stroke: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<svg id='par' width="100" height="40">
  <rect id='ch' width="40" height="40" style="fill:rgb(0,0,255)" />
</svg>

【问题讨论】:

  • 我不清楚你想要什么。将外部 svg 元素包裹在内部 svg 元素宽度/高度 40 中吗?

标签: javascript jquery html css svg


【解决方案1】:

防止 svg 溢出的是您的 UA 样式中的 svg:not(:root){overflow:hidden}(在 chrome 上),

因此,如果您将其设置为 visible,它将起作用:

svg:not(:root) { overflow : visible; }

FIDDLE

【讨论】:

  • 那不正确.. 在默认的 svg rect 行为中,如果我们将笔划设置为 100 但实际矩形宽度为 50,则矩形宽度的大小不会增加,并在矩形内设置边框
【解决方案2】:

你的意思是这样吗?更改填充颜色会更简单。

其他方法是创建一个 clipPath 或使用 clip CSS 属性。

// In mouse hover, I have set the style:
var links = $('#ch');
links.hover(function() {
  $('#ch').attr('class', 'st');
}, function() { //mouseout
  $('#ch').attr('class', '');
});
.st {
  stroke-width: 60px;
  stroke: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<svg id='par' width="100" height="40">
  <svg width="40" height="40">
      <rect id='ch' width="40" height="40" style="fill:rgb(0,0,255)" />
  </svg>
</svg>

【讨论】:

    【解决方案3】:

    找到答案,

    <svg width="100" height="100">
        <defs>
            <clipPath id="clipRect">
                <rect width="40" height="40" />
            </clipPath>
        </defs>
        <rect id ='ch' width="40" height="40" clip-path=url(#clipRect)   style="fill:rgb(0,0,255)" stroke-width="8px" stroke="red" />
    </svg>
    

    Sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2014-06-26
      • 2013-02-09
      • 2014-07-04
      相关资源
      最近更新 更多