拖拽元素更改 border-randus
效果演示
拖拽我
圆角了
代码展示
vue
<script setup>
import { onMounted } from "vue";
const initDrag = (vm, _vm) => {
let [startX, startY, startLeft, startTop] = [
0,
0,
vm.offsetLeft,
vm.offsetTop,
];
vm.addEventListener("mousedown", function (e) {
startX = e.clientX;
startY = e.clientY;
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
vm.style.transition = "";
_vm.style.transition = "";
});
function onMouseMove(e) {
vm.style.left = e.clientX - startX + startLeft + "px";
vm.style.top = e.clientY - startY + startTop + "px";
_vm.style.borderRadius =
(
Math.sqrt(
Math.pow(e.clientX - startX, 2) + Math.pow(e.clientY - startY, 2)
) / 2
).toFixed(2) + "px";
}
function onMouseUp() {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
vm.style.left = startLeft + "px";
vm.style.top = startTop + "px";
vm.style.transition = "0.5s all ease";
_vm.style.transition = "0.5s all ease";
_vm.style.borderRadius = "0px";
}
};
const initPhoneDrag = (vm, _vm) => {
let [startX, startY, startLeft, startTop] = [
0,
0,
vm.offsetLeft,
vm.offsetTop,
];
vm.addEventListener("touchstart", function (e) {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
document.addEventListener("touchmove", onTouchMove);
document.addEventListener("touchend", onTouchEnd);
vm.style.transition = "";
_vm.style.transition = "";
});
function onTouchMove(e) {
e.preventDefault(); // 防止滚动屏幕
vm.style.left = e.touches[0].clientX - startX + startLeft + "px";
vm.style.top = e.touches[0].clientY - startY + startTop + "px";
_vm.style.borderRadius =
(
Math.sqrt(
Math.pow(e.touches[0].clientX - startX, 2) +
Math.pow(e.touches[0].clientY - startY, 2)
) / 2
).toFixed(2) + "px";
}
function onTouchEnd() {
document.removeEventListener("touchmove", onTouchMove);
document.removeEventListener("touchend", onTouchEnd);
vm.style.left = startLeft + "px";
vm.style.top = startTop + "px";
vm.style.transition = "0.5s all ease";
_vm.style.transition = "0.5s all ease";
_vm.style.borderRadius = "0px";
}
};
onMounted(() => {
const box1 = document.querySelector(".draggable-box .box1");
const box2 = document.querySelector(".draggable-box .box2");
try {
initDrag(box1, box2);
initPhoneDrag(box1, box2);
} catch (error) {}
});
</script>
vue
<template>
<section class="draggable-box">
<div class="box1">拖拽我</div>
<div class="box2">圆角了</div>
</section>
</template>
vue
<style lang="scss">
.draggable-box {
text-align: center;
.box1 {
width: 260px;
position: absolute;
cursor: move;
background-color: var(--vp-c-border);
height: 200px;
z-index: 1;
}
.box2 {
width: 260px;
position: relative;
cursor: pointer;
background-color: var(--vp-c-divider);
height: 200px;
}
}
</style>