我有一个棒球场的 SVG,我试图通过其父容器的属性设置它的宽度和高度。
这是我的 fiddle :https://jsfiddle.net/a5mz90jy/6/
这是我的 Javascript:
const svgBaseballField = document.getElementById('diamond');
console.log(svgBaseballField);
const svgContainer = document.getElementsByClassName('svg_container');
console.log(svgContainer);
const svgContainerHeight = svgContainer.clientHeight;
console.log(svgContainerHeight);
const svgContainerWidth = svgContainer.clientWidth;
svgBaseballField.setAttribute("width", svgContainerWidth);
svgBaseballField.setAttribute("height", svgContainerHeight);
svgBaseballField.setAttribute("viewBox", "0 0 100 100");
我知道出了点问题,因为 svgContainerHeight 和 svgContainerWidth 未定义。我也知道我需要设置视口(viewport)。
我之前也检查过这个: How can I make an svg scale with its parent container?
最佳答案
您链接到的 SVG 有一个固定的 width
和 height
(650 x 500),因此您将无法按照现在的方式进行操作(即通过 <object>
。
你有两个选择:
将 SVG 复制到本地并进行修改。添加
viewBox
属性并更改width
和height
至"100%"
.<svg ... width="100%" height="100%" viewBox="0 0 650 500" ... >
另一种解决方案是将 SVG 作为背景图像并利用 CSS 背景大小调整属性。
.svg_container { width: 75%; height: 100%; background: url(https://upload.wikimedia.org/wikipedia/commons/8/89/Baseball_diamond_clean.svg) blue; background-repeat: no-repeat; background-size: contain; }
关于javascript - 如何使用 JavaScript 使 SVG 缩放到父容器的全高和全宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581732/