在鼠标悬停时添加连接器,类似于draw.io的功能,通常涉及到前端开发中的交互设计和图形绘制。这种功能可以通过HTML、CSS和JavaScript来实现。基本思路是监听鼠标的悬停事件,然后在特定元素之间动态绘制连接器。
以下是一个简单的示例代码,展示如何在鼠标悬停时添加直线连接器:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hover Connector Example</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
display: inline-block;
}
.connector {
position: absolute;
background-color: black;
z-index: 1000;
}
</style>
</head>
<body>
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<script>
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');
let connector = null;
function createConnector() {
if (connector) {
connector.remove();
}
const x1 = box1.offsetLeft + box1.offsetWidth / 2;
const y1 = box1.offsetTop + box1.offsetHeight / 2;
const x2 = box2.offsetLeft + box2.offsetWidth / 2;
const y2 = box2.offsetTop + box2.offsetHeight / 2;
connector = document.createElement('div');
connector.className = 'connector';
connector.style.width = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) + 'px';
connector.style.height = '2px';
connector.style.left = x1 + 'px';
connector.style.top = y1 + 'px';
connector.style.transformOrigin = 'left center';
connector.style.transform = `rotate(${Math.atan2(y2 - y1, x2 - x1)}rad)`;
document.body.appendChild(connector);
}
box1.addEventListener('mouseenter', createConnector);
box2.addEventListener('mouseenter', createConnector);
</script>
</body>
</html>
getBoundingClientRect()
方法获取元素的精确位置。visibility
属性来控制显示和隐藏。requestAnimationFrame
来优化动画效果,减少重绘次数。通过以上方法,可以实现一个简单但功能强大的鼠标悬停连接器效果。
领取专属 10元无门槛券
手把手带您无忧上云