基于Vue实现图片在指定区域内移动的思路详解

2020-06-13 10:23:19易采站长站整理

  当图片比要显示的区域大时,需要将多余的部分隐藏掉,我们可以通过绝对定位来实现,并通过动态修改图片的left值和top值从而实现图片的移动。具体实现效果如下图,如果我们移动的是div 实现思路相仿。

此处需要注意的是

我们在移动图片时,需要通过

draggable="false"
将图片的
 <img src="/static/pano-dev/test/image-2.jpg" draggable="false" />,
否则按下鼠标监听onmousemove事件时监听不到

然后还需要禁用图片的选中css


/*禁止元素选中*/
-moz-user-select: none; /*火狐*/
-webkit-user-select: none; /*webkit浏览器*/
-ms-user-select: none; /*IE10*/
-khtml-user-select: none; /*早期浏览器*/
user-select: none;

Vue 代码


<style lang="less" scoped>
@import url("./test.less");
</style>
<template>
<div class="page">
<div class="image-move-wapper">
<div class="image-show-box" ref="imageShowBox">
<div class="drag-container" ref="dragContainer" :style="'left:' + dragContainer.newPoint.left+'px; top:' + dragContainer.newPoint.top+'px'" @mousedown="DragContainerMouseDown">
<div class="drag-image-box">
<img src="/static/pano-dev/test/image-2.jpg" draggable="false" />
<div class="point" style="left:10%; top:10%" @mousedown="PointMouseDown"></div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
dragContainer: {
box: {
w: 0,
h: 0
},
point: {
left: 0,
top: 0
},
newPoint: {
left: 0,
top: 0
}
},
mousePoint: {
x: 0,
y: 0
},
imageShowBox: {
box: {
w: 0,
h: 0
},
dragcheck: {
h: true,
v: true
}
}
};
},
updated() {
let _this = this;
// 确保DOM元素已经渲染成功,然后获取拖拽容器和显示区域的大小
_this.$nextTick(function() {
_this.dragContainer.box = {
w: _this.$refs.dragContainer.offsetWidth,
h: _this.$refs.dragContainer.offsetHeight
};
_this.imageShowBox.box = {
w: _this.$refs.imageShowBox.offsetWidth,
h: _this.$refs.imageShowBox.offsetHeight
};
// 判断是否允许拖拽
_this.imageShowBox.dragcheck = {
h: _this.imageShowBox.box.w > _this.dragContainer.box.w ? false : true,
v: _this.imageShowBox.box.h > _this.dragContainer.box.h ? false : true