<template>
<div class="image-container" @mousedown="startDrag" @mousemove="drag" @mouseup="endDrag">
<img src="path/to/image.jpg" alt="My Image" ref="imageRef">
</div>
</template>
在組件的?<script>
?標簽中,定義相關的數(shù)據(jù)和方法。首先,使用 Vue 的?ref
?函數(shù)創(chuàng)建一個對圖片元素的引用:
<script>
import { ref } from 'vue';
export default {
setup() {
const imageRef = ref(null);
// ...
return {
imageRef,
// ...
};
},
};
</script>
接下來,實現(xiàn)選中時出現(xiàn)邊框的效果。你可以通過設置 CSS 樣式來實現(xiàn)這一點。以下是一個簡單的示例:
.image-container {
position: relative;
}
.image-container.selected {
outline: 2px solid blue;
}
.image-container.selected::before {
content: '';
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
border: 1px dashed blue;
}
在組件的?<template>
?中,為選中的容器元素動態(tài)綁定?selected
?類名??梢酝ㄟ^監(jiān)聽鼠標事件來實現(xiàn)這一點。例如,在?startDrag
?方法中添加以下代碼:
function startDrag() {
// 添加選中樣式
imageRef.value.parentElement.classList.add('selected');
// ...
}
在 endDrag
方法中移除選中樣式:文章來源:http://www.zghlxwxcb.cn/news/detail-641159.html
function endDrag() {
// 移除選中樣式
imageRef.value.parentElement.classList.remove('selected');
// ...
}
實現(xiàn)拖動圖片的功能。在?drag
?方法中,計算鼠標移動的距離,并將其應用于圖片元素的位置。這里可以使用鼠標事件的?clientX
?和?clientY
?屬性來獲取鼠標的位置。以下是一個簡單的示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-641159.html
function drag(event) {
// 確保只有當圖片被選中時才會觸發(fā)拖動操作
if (imageRef.value.parentElement.classList.contains('selected')) {
const imageElement = imageRef.value;
const containerElement = imageElement.parentElement;
const deltaX = event.clientX - containerElement.offsetLeft;
const deltaY = event.clientY - containerElement.offsetTop;
imageElement.style.left = `${deltaX}px`;
imageElement.style.top = `${deltaY}px`;
// ...
}
}
到了這里,關于Vue 3 + TypeScript + Vite 項目中,實現(xiàn)選中圖片移動的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!