gpt4 book ai didi

css - 删除 100% 宽度 SVG 图形的底部间距

转载 作者:行者123 更新时间:2023-11-28 12:33:45 24 4
gpt4 key购买 nike

我有一个带有预设视口(viewport)的 svg 框。我想显示它以使其 100% 跨越。但是正在发生的事情是它在下面增加了空间。我怎样才能摆脱这个?我宁愿不必修改视口(viewport)和内部组件大小(它们是从需要这些的其他一些工具生成的)但我可以添加/修改 svg 标签的属性(例如纵横比)。我做了一个 fiddle - http://jsfiddle.net/cyberwombat/2MLwx/1/ - 我希望黑色框周围的红色边框为 2px。我已经尝试了几种 preserveAspectRatio 的变体,但到目前为止没有成功。

<!DOCTYPE html>
<head>
<style>
.frame {
margin:100px 100px 0 100px;
background-color:yellow;
}
.wrapper {
border:1px solid red;
padding:2px;
}
svg {

}
</style>
</head>
<body>
<div class="frame">
<div class="wrapper">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMinYMin meet" viewBox="0 0 800 150" width="100%" version="1.1">
<rect transform="matrix(1,0,0,1,0,0)" x="0" y="0" width="100%" height="100%" r="0" rx="0" ry="0" fill="#000" stroke="#000"></rect>
</svg>
</div>
Hello
</div>

</body>
</html>

最佳答案

使用 javascript,您可以将 svg 元素的尺寸更改为 View 框:

var a = document.getElementsByTagName('svg')[0];
var width = parseInt(a.getAttribute("viewBox").split(/\s+/)[2], 10);
var height = parseInt(a.getAttribute("viewBox").split(/\s+/)[3], 10);

a.style.width = width + 'px';
a.style.height = height + 'px';

// You have to update the parent's dimensions too or else it has no idea its
// child changed dimensions
var b = document.getElementsByClassName('wrapper')[0];
var c = document.getElementsByClassName('frame')[0];
b.style.width = (width + 2) + 'px'; // Hard coded values based on your padding
c.style.width = (width + 4) + 'px'; // Hard coded values based on your padding

Demo here

如果您的 View 框不是从 0,0 开始,您可以通过减去起始值来找到宽度,如下所示:

var width = parseInt(a.getAttribute("viewBox").split(/\s+/)[2], 10) 
- parseInt(a.getAttribute("viewBox").split(/\s+/)[0], 10);
var height = parseInt(a.getAttribute("viewBox").split(/\s+/)[3], 10)
- parseInt(a.getAttribute("viewBox").split(/\s+/)[1], 10);

如果你想动态地包含宽度的填充(不知道为什么你要改变填充,但这不是我的问题)它更复杂,但它看起来像这样

var containerPadding = parseInt(window.getComputedStyle(containerVar, null).getPropertyValue('padding-left'), 10) 
+ parseInt(window.getComputedStyle(containerVar, null).getPropertyValue('padding-right'), 10);

编辑

我现在知道您不明白的是:您的问题仅由 CSS 引起。您永远不会为包装器或框架设置宽度/高度,因此他们会尝试使用所有窗口减去您拥有的边距。包装器无法根据 svg 的高度/宽度自行调整大小,除非您将其更改为默认值

在那种情况下,我会像您建议的那样使用 CSS 为框架和容器设置必要的尺寸。我本来以为你需要动态改变尺寸

关于css - 删除 100% 宽度 SVG 图形的底部间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18089505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com