Todo:补充细节 & 分析
DOM实现
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>div连线demo</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
<div id="e1" class="element element_1">e1</div>
<div id="e2" class="element element_2">e2</div>
<div id="e3" class="element element_3">e3</div>
<div id="e4" class="element element_4">e4</div>
<div id="e5" class="element element_5">e5</div>
</body>
</html>
Style实现
<style type="text/css">
.element {
position: absolute;
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
background-color: lightblue;
}
.element_1 {
top: 100px;
left: 50px;
}
.element_2 {
top: 100px;
left: 150px;
}
.element_3 {
top: 100px;
left: 250px;
}
.element_4 {
top: 300px;
left: 150px;
}
.element_5 {
top: 300px;
left: 350px;
}
</style>
JavaScript实现
<script type="text/javascript">
function drawLine(obj1, obj2) {
// 起点坐标
let x1 = obj1.getBoundingClientRect().left + obj1.clientWidth;
let y1 = obj1.getBoundingClientRect().top + obj1.clientHeight / 2;
// 终点坐标
let x2 = obj2.getBoundingClientRect().left;
let y2 = obj2.getBoundingClientRect().top + obj2.clientHeight / 2;
// 计算连接线长度
let length = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
// 计算连接线旋转弧度值
let rad = Math.atan2((y2 - y1), (x2 - x1));
// 连接线未旋转前,起点坐标计算
let top = (y1 + y2) / 2;
let left = (x1 + x2) / 2 - length / 2;
// 创建连接线 dom 节点,并设置样式
let line = document.createElement('div');
let style =
`
position: absolute;
background-color: tan;
height: 1px;
top: ${top}px;
left:${left}px;
width:${length}px;
transform: rotate(${rad}rad);
`;
line.setAttribute('style', style);
document.body.appendChild(line);
}
drawLine(document.getElementById('e1'), document.getElementById('e2'));
drawLine(document.getElementById('e2'), document.getElementById('e3'));
drawLine(document.getElementById('e1'), document.getElementById('e4'));
drawLine(document.getElementById('e1'), document.getElementById('e5'));
</script>
Comments | NOTHING