From 83574cc901acc153bf2a2070ccc4f838f27efd76 Mon Sep 17 00:00:00 2001 From: tangly1024 Date: Thu, 12 May 2022 12:50:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8B=96=E6=8B=BD=E7=BB=84=E4=BB=B6=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E8=BE=B9=E7=BC=98=E5=90=B8=E9=99=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/Draggable.js | 27 +++++++++++++++++++++++++++ components/ThemeSwitch.js | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/components/Draggable.js b/components/Draggable.js index 372cfd78..97a448be 100644 --- a/components/Draggable.js +++ b/components/Draggable.js @@ -52,6 +52,7 @@ export const Draggable = (props) => { if (currentObj) { currentObj.style.left = event.mx - offsetX + 'px'// 定义拖动元素的x轴距离 currentObj.style.top = event.my - offsetY + 'px'// 定义拖动元素的y轴距离 + checkInWindow() } } @@ -87,11 +88,37 @@ export const Draggable = (props) => { return false } + /** + * 若超出窗口则吸附。 + */ function checkInWindow() { // 检查是否悬浮在窗口内 + for (const drag of draggableElements) { + // 判断鼠标点击的区域是否是拖拽框内 + const { offsetHeight, offsetWidth, offsetTop, offsetLeft } = drag.firstElementChild + const { clientHeight, clientWidth } = document.documentElement + if (offsetTop < 0) { + drag.firstElementChild.style.top = 0 + } + if (offsetTop > (clientHeight - offsetHeight)) { + drag.firstElementChild.style.top = clientHeight - offsetHeight + 'px' + } + if (offsetLeft < 0) { + drag.firstElementChild.style.left = 0 + } + if (offsetLeft > (clientWidth - offsetWidth)) { + drag.firstElementChild.style.left = clientWidth - offsetWidth + 'px' + } + } } window.addEventListener('resize', checkInWindow) + + return () => { + return () => { + window.removeEventListener('resize', checkInWindow) + } + } }, []) return
diff --git a/components/ThemeSwitch.js b/components/ThemeSwitch.js index a240ce1b..2a8a76e7 100644 --- a/components/ThemeSwitch.js +++ b/components/ThemeSwitch.js @@ -13,7 +13,7 @@ export function ThemeSwitch() {
-
{theme}
+
{theme}