2 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
如果您已經(jīng)添加了一個(gè)固定在要調(diào)整大小的角上的調(diào)整大小按鈕div
:
監(jiān)聽(tīng)
mousedown
按鈕上的事件在聽(tīng)者中,
存儲(chǔ)起始尺寸和點(diǎn)擊位置
添加一個(gè)
mousemove
監(jiān)聽(tīng)onMouseMove
器來(lái)document.body
跟蹤光標(biāo)位置添加一個(gè)監(jiān)聽(tīng)器,當(dāng)拖動(dòng)被釋放時(shí)
mouseup
移除mouseMove
使用光標(biāo)位置的變化來(lái)
div
適當(dāng)?shù)卣{(diào)整大小。
例子:
const { useState } = React;
function Resizeable({ children }) {
const [size, setSize] = useState({ x: 400, y: 300 });
const handler = (mouseDownEvent) => {
const startSize = size;
const startPosition = { x: mouseDownEvent.pageX, y: mouseDownEvent.pageY };
function onMouseMove(mouseMoveEvent) {
setSize(currentSize => ({
x: startSize.x - startPosition.x + mouseMoveEvent.pageX,
y: startSize.y - startPosition.y + mouseMoveEvent.pageY
}));
}
function onMouseUp() {
document.body.removeEventListener("mousemove", onMouseMove);
// uncomment the following line if not using `{ once: true }`
// document.body.removeEventListener("mouseup", onMouseUp);
}
document.body.addEventListener("mousemove", onMouseMove);
document.body.addEventListener("mouseup", onMouseUp, { once: true });
};
return (
<div id="container" style={{ width: size.x, height: size.y }}>
<button id="draghandle" type="button" onMouseDown={handler} >Resize</button>
</div>
);
}
ReactDOM.render(<Resizeable />, document.getElementById("root"));
#root {
height: 100vh;
width: 100vw;
}
#container {
position: relative;
background-color: lightpink;
border: solid red 1px;
}
#draghandle {
position: absolute;
bottom: 0;
right: 0;
transform: translate(50%, 50%);
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
請(qǐng)注意,只有mousedown
事件應(yīng)用于button
,而其他處理程序應(yīng)用于document.body
。這可確??焖賹⒐鈽?biāo)移離button
不會(huì)導(dǎo)致錯(cuò)過(guò)事件。

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
所以你需要三個(gè)信息來(lái)做到這一點(diǎn)。鼠標(biāo)第一次單擊調(diào)整大小手柄時(shí)的位置、鼠標(biāo)移動(dòng)時(shí)的位置以及元素的高度和寬度。
從獲取元素的高度和寬度開(kāi)始:
const [height, setHeight] = useState({ height: 20 }); // initialise to 20px
const [dragging, setDragging] = useState(false);
/** -- snip -- **/
<img style={{ height }} /* snip */ />
有了圖片,html會(huì)自動(dòng)為你處理縮放,所以你只需要應(yīng)用height屬性,width就會(huì)自動(dòng)縮放。
現(xiàn)在我們需要獲取resize手柄的鼠標(biāo)onClick的位置。我假設(shè)您已經(jīng)有了手柄的樣式,所以我們可以忽略它:
const [mouseStart, setMouseStart] = useState({ x: 0, y: 0 });
/** -- snip -- */
<ResizeHandle
onMouseDown={e => {
setDragging(true);
setMouseStart({ x: e.offsetX, y: e.offsetY });
}}
/>
然后你需要監(jiān)聽(tīng) mouseMove 事件并適當(dāng)調(diào)整 img 的大小 - 這應(yīng)該在父組件中完成:
<div
onMouseMove={e => {
if (dragging) {
const pixelDifference = Math.max(mouseStart.x - e.offsetX, mouseStart.y - e.offsetY);
setHeight(height + pixelDifference);
}
}}
onMouseUp={() => setDragging(false)}
>
<img /* snip */ />
<ResizeHandle /* snip */ />
</div>
添加回答
舉報(bào)