一个div里面有多个机柜,实现以鼠标当前位置为原点缩放
时间: 2024-05-04 21:21:35 浏览: 12
要实现以鼠标当前位置为原点缩放,可以使用以下步骤:
1. 获取鼠标当前位置相对于div的坐标,可以使用event.clientX和event.clientY获取鼠标的绝对位置,再减去div的左上角的坐标,即可得到相对于div的坐标。
2. 根据缩放比例计算出新的机柜大小。假设当前机柜大小为w和h,缩放比例为s,那么新的机柜大小为w * s和h * s。
3. 计算鼠标在缩放后的机柜中的位置。假设鼠标相对于div的坐标为(x, y),缩放前机柜左上角的坐标为(x0, y0),缩放后机柜左上角的坐标为(x1, y1),那么鼠标在缩放后的机柜中的坐标为((x - x0) * s + x1, (y - y0) * s + y1)。
4. 根据缩放后的机柜大小和鼠标在缩放后的机柜中的位置,重新设置机柜的大小和位置。
下面是一个示例代码,假设机柜的class为cabinet:
```javascript
const div = document.getElementById('div');
const cabinets = document.getElementsByClassName('cabinet');
div.addEventListener('wheel', (event) => {
event.preventDefault(); // 阻止默认滚动事件
const mouseX = event.clientX - div.getBoundingClientRect().left;
const mouseY = event.clientY - div.getBoundingClientRect().top;
const scale = event.deltaY > 0 ? 0.9 : 1.1; // 根据滚动方向计算缩放比例
Array.from(cabinets).forEach(cabinet => {
const rect = cabinet.getBoundingClientRect();
const x0 = rect.left - div.getBoundingClientRect().left;
const y0 = rect.top - div.getBoundingClientRect().top;
const w = rect.width;
const h = rect.height;
const s = scale;
const x1 = (mouseX - x0) * s + x0;
const y1 = (mouseY - y0) * s + y0;
const w1 = w * s;
const h1 = h * s;
cabinet.style.width = `${w1}px`;
cabinet.style.height = `${h1}px`;
cabinet.style.left = `${x1}px`;
cabinet.style.top = `${y1}px`;
});
});
```