vue一个盒子内部包含另一个盒子,内部盒子可以自由移动,放大及缩小
时间: 2024-03-11 09:46:56 浏览: 182
你可以使用Vue.js结合CSS3和HTML5的Draggable API来实现一个盒子内部包含另一个盒子,内部盒子可以自由移动、放大和缩小的效果。下面是一个示例代码,可以实现这个效果:
HTML结构:
```html
<div id="app">
<div class="container" ref="container">
<div class="box">
<div class="inner-box"
ref="innerBox"
:style="{ transform: `translate(${x}px, ${y}px) scale(${scale})` }"
@mousedown="handleMouseDown"
@mouseup="handleMouseUp">
Inner Box
</div>
</div>
</div>
</div>
```
CSS样式:
```css
.container {
width: 400px;
height: 400px;
border: 1px solid #ccc;
position: relative;
}
.box {
width: 200px;
height: 200px;
border: 1px solid #ccc;
position: absolute;
top: 100px;
left: 100px;
}
.inner-box {
width: 100px;
height: 100px;
border: 1px solid #ccc;
position: absolute;
top: 50px;
left: 50px;
cursor: move;
}
```
Vue.js代码:
```js
new Vue({
el: '#app',
data: {
x: 0,
y: 0,
scale: 1,
isDragging: false,
initialMouseX: 0,
initialMouseY: 0,
initialX: 0,
initialY: 0,
},
methods: {
handleMouseDown(event) {
this.isDragging = true;
this.initialMouseX = event.clientX;
this.initialMouseY = event.clientY;
this.initialX = this.x;
this.initialY = this.y;
},
handleMouseUp(event) {
this.isDragging = false;
},
},
mounted() {
const innerBox = this.$refs.innerBox;
const container = this.$refs.container;
const containerRect = container.getBoundingClientRect();
const innerBoxRect = innerBox.getBoundingClientRect();
const aspectRatio = innerBoxRect.width / innerBoxRect.height;
innerBox.style.width = `${innerBoxRect.width}px`;
innerBox.style.height = `${innerBoxRect.height}px`;
const resizeObserver = new ResizeObserver(() => {
const innerBoxRect = innerBox.getBoundingClientRect();
innerBox.style.width = `${innerBoxRect.width}px`;
innerBox.style.height = `${innerBoxRect.width / aspectRatio}px`;
});
resizeObserver.observe(innerBox);
document.addEventListener('mousemove', (event) => {
if (this.isDragging) {
const deltaX = event.clientX - this.initialMouseX;
const deltaY = event.clientY - this.initialMouseY;
this.x = this.initialX + deltaX;
this.y = this.initialY + deltaY;
}
});
document.addEventListener('wheel', (event) => {
const delta = event.deltaY;
const scaleFactor = delta < 0 ? 1.1 : 0.9;
this.scale *= scaleFactor;
});
},
});
```
在上面的代码中,我们使用了Vue.js的响应式数据来控制内部盒子的位置和缩放比例。当鼠标按下时,我们记录下初始位置和初始鼠标位置,并将isDragging标志设置为true,表示正在拖动内部盒子。当鼠标抬起时,我们将isDragging标志设置为false,表示停止拖动。
我们还添加了一个ResizeObserver来监听内部盒子的大小变化,并根据它的宽高比来调整内部盒子的高度。
最后,我们在document上监听鼠标移动事件和鼠标滚轮事件,当鼠标移动时,根据鼠标的偏移量来更新内部盒子的位置;当鼠标滚动时,根据滚动的方向来更新内部盒子的缩放比例。
阅读全文