获取svg宽高
时间: 2023-06-28 21:07:08 浏览: 58
要获取SVG的宽高,可以使用以下两种方法:
1. JavaScript 方法:
可以使用 JavaScript 获取 SVG 元素的 width 和 height 属性,示例代码如下:
```javascript
const svg = document.querySelector('svg');
const width = svg.getAttribute('width');
const height = svg.getAttribute('height');
console.log(`Width: ${width}, Height: ${height}`);
```
2. CSS 方法:
可以使用 CSS 的 width 和 height 属性来获取 SVG 元素的宽高,示例代码如下:
```css
svg {
width: 100px;
height: 50px;
}
```
在 CSS 中设置了 SVG 元素的宽高后,可以使用 JavaScript 获取计算后的宽高,示例代码如下:
```javascript
const svg = document.querySelector('svg');
const width = getComputedStyle(svg).getPropertyValue('width');
const height = getComputedStyle(svg).getPropertyValue('height');
console.log(`Width: ${width}, Height: ${height}`);
```