Vue3中實(shí)現(xiàn)div拖拽功能
更新時間:2024年03月11日 10:15:28 作者:zhige@
這篇文章主要介紹了Vue3中實(shí)現(xiàn)div拖拽功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
1.創(chuàng)建一個div
<template> <div class="draggable" :style="{ left: `${x}px`, top: `${y}px` }" @mousedown="startDrag"> 拖拽我 </div> </template>
2.typescript代碼
<script setup> import { ref } from 'vue'; // 用于存儲元素X和Y位置的響應(yīng)性引用 const x = ref(500); const y = ref(500); // 是否正在拖動的標(biāo)志 const isDragging = ref(false); // 開始拖動的函數(shù) const startDrag = (event) => { // 記錄初始鼠標(biāo)位置 const initialMouseX = event.clientX; const initialMouseY = event.clientY; // 記錄初始元素位置 const initialX = x.value; const initialY = y.value; // 開始拖動,設(shè)置為true isDragging.value = true; // 當(dāng)鼠標(biāo)移動時執(zhí)行的函數(shù) const dragging = (moveEvent) => { // 只有在拖動時才執(zhí)行 if (isDragging.value) { // 計算鼠標(biāo)移動的距離 const deltaX = moveEvent.clientX - initialMouseX; const deltaY = moveEvent.clientY - initialMouseY; // 更新元素的位置 x.value = initialX + deltaX; y.value = initialY + deltaY; } }; // 鼠標(biāo)釋放時停止拖動的函數(shù) const stopDrag = () => { // 結(jié)束拖動,設(shè)置為false isDragging.value = false; // 移除事件監(jiān)聽器 document.removeEventListener('mousemove', dragging); document.removeEventListener('mouseup', stopDrag); }; // 添加鼠標(biāo)移動和釋放時的事件監(jiān)聽器 document.addEventListener('mousemove', dragging); document.addEventListener('mouseup', stopDrag); }; </script>
3.CSS樣式
<style> .draggable { width: 550px; height: 550px; border: 1px solid #000; position: fixed; cursor: grab; /* 設(shè)置鼠標(biāo)樣式為可抓取狀態(tài) */ z-index: 100; } </style>
到此這篇關(guān)于Vue3中實(shí)現(xiàn)div拖拽功能的文章就介紹到這了,更多相關(guān)Vue3 div拖拽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue2+springsecurity權(quán)限系統(tǒng)的實(shí)現(xiàn)
本文主要介紹了vue2+springsecurity權(quán)限系統(tǒng)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05基于Vue實(shí)現(xiàn)HTML轉(zhuǎn)PDF并導(dǎo)出
這篇文章主要為大家介紹了三種方法,可以實(shí)現(xiàn)將HTML頁面轉(zhuǎn)為PDF并實(shí)現(xiàn)下載。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以學(xué)習(xí)一下2022-04-04vscode中prettier和eslint換行縮進(jìn)沖突的問題
這篇文章主要介紹了vscode中prettier和eslint換行縮進(jìn)沖突的問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vscode中的vue項(xiàng)目報錯Property ‘xxx‘ does not exist on type ‘Combin
這篇文章主要介紹了vscode中的vue項(xiàng)目報錯Property ‘xxx‘ does not exist on type ‘CombinedVueInstance<{ readyOnly...Vetur(2339),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09