使用svg+div来画两个长方形中间用箭头线连接
时间: 2024-03-08 19:48:37 浏览: 18
可以使用以下 HTML、CSS 和 SVG 代码来画两个长方形中间用箭头线连接:
```html
<div style="position: relative; width: 200px; height: 100px;">
<!-- 第一个长方形 -->
<svg viewBox="0 0 100 100" style="position: absolute; left: 20px; top: 20px;">
<rect x="0" y="0" width="100" height="100" fill="#f00" />
</svg>
<!-- 第二个长方形 -->
<svg viewBox="0 0 100 100" style="position: absolute; left: 120px; top: 20px;">
<rect x="0" y="0" width="100" height="100" fill="#0f0" />
</svg>
<!-- 箭头线 -->
<svg viewBox="0 0 200 100" style="position: absolute; left: 0; top: 0;">
<line x1="80" y1="50" x2="120" y2="50" stroke="#00f" stroke-width="2" marker-end="url(#arrow)" />
<!-- 定义箭头 -->
<defs>
<marker id="arrow" markerWidth="10" markerHeight="10" refX="8" refY="5" orient="auto" markerUnits="strokeWidth">
<path d="M0,0 L0,10 L8,5 z" fill="#00f" />
</marker>
</defs>
</svg>
</div>
```
其中,`div` 元素用来创建包裹 SVG 元素的容器,`position: relative;` 属性用来指定容器的定位方式,`width` 和 `height` 属性用来指定容器的大小。每个 SVG 元素用来创建长方形或箭头线,`viewBox` 属性用来指定 SVG 的视口大小和位置,`style` 属性用来指定 SVG 元素的定位方式和位置。箭头线的 SVG 元素需要放在最后面,以便覆盖前面的 SVG 元素。
需要注意的是,SVG 元素默认是 inline 元素,无法设置宽度和高度,需要用 CSS 的 `position` 属性和 `left`、`top` 属性来控制位置和大小。