And*_* R. 5 javascript jquery svg inline
我试图解决这个问题已经超过一天了,但我找不到答案。我的问题是我需要缩放 SVG 图像(响应式设计)。我需要在客户端操作 SVG 代码,所以通过 img 标签嵌入它不是一个选项。因此,我尝试改用内嵌图像。但是,要正确缩放它,似乎我需要设置 viewBox 属性。SVG 文件是由某些无法自行设置边界框的软件生成的,因此我的想法是为此目的使用 JavaScript。
问题是我的软件使用了我无法修改的库中的各种选项卡控件。我不能只得到边界框,因为它最初没有呈现,因此我只得到零(在 Chrome 中)或错误消息(在 Firefox 中)。
我需要的是一种无需实际渲染对象即可获得边界框大小的方法。无法操作库用于显示和隐藏选项卡的显示参数。
有任何想法吗?
一个想法是将 SVG 复制到另一个可见的 div 中,但我不知道这是否能解决问题。我不知道该怎么做。
此致
根据之前的答案,我getBBox对我的应用程序 init 进行了猴子修补,以便它将透明地应用黑客攻击。
现在我可以getBBox直接调用任何元素,无论它是否附加。
_getBBox = SVGGraphicsElement.prototype.getBBox;
SVGGraphicsElement.prototype.getBBox = function() {
var bbox, tempDiv, tempSvg;
if (document.contains(this)) {
return _getBBox.apply(this);
} else {
tempDiv = document.createElement("div");
tempDiv.setAttribute("style", "position:absolute; visibility:hidden; width:0; height:0");
if (this.tagName === "svg") {
tempSvg = this.cloneNode(true);
} else {
tempSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
tempSvg.appendChild(this.cloneNode(true));
}
tempDiv.appendChild(tempSvg);
document.body.appendChild(tempDiv);
bbox = _getBBox.apply(tempSvg);
document.body.removeChild(tempDiv);
return bbox;
}
};
Run Code Online (Sandbox Code Playgroud)
您可以将其克隆到可见的 svg,然后 getBBox。
添加到你的html中:
<div style="position:absolute;left:-9999cm;top:-9999cm;visibility:hidden;">
<svg id="svg1" xmlns="http://www.w3.org/2000/svg"></svg>
</div>
Run Code Online (Sandbox Code Playgroud)
添加到您的 JavaScript 中:
function getBBox(elem){
var svg1 = document.getElementById('svg1'), e = elem.cloneNode(true);
e.style.display = "inline";
svg1.appendChild(e);
var b = e.getBBox();
svg1.removeChild(e);
return b;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2501 次 |
| 最近记录: |