如何在div完成resize操作后调用指定函数?
实现div调整大小完成后触发函数
要实现只在div调整大小结束后(鼠标从调整手柄抬起时)触发函数,我们可以通过监听鼠标的mousedown、mouseup事件,结合调整状态标记来实现——因为原生并没有针对元素resize的结束事件。
具体实现代码
<div id="item"></div>
div{ resize: both; overflow: hidden; height: 10rem; width: 10rem; border: solid 0.5rem black; }
const item = document.getElementById('item'); let isResizing = false; // 监听鼠标按下,标记是否开始调整 item.addEventListener('mousedown', (e) => { const rect = item.getBoundingClientRect(); const handleSize = 16; // 调整手柄的大致尺寸,可按需修改 // 判断鼠标是否点击在右下角的调整手柄上 const isOnHandle = e.clientX >= rect.right - handleSize && e.clientY >= rect.bottom - handleSize; if (isOnHandle) { isResizing = true; } }); // 监听鼠标抬起,触发完成回调 window.addEventListener('mouseup', () => { if (isResizing) { isResizing = false; // 调用调整完成后要执行的函数 handleResizeComplete(); } }); // 自定义的调整完成回调函数 function handleResizeComplete() { console.log('调整大小完成!'); const { width, height } = item.getBoundingClientRect(); console.log(`当前尺寸:宽${Math.round(width)}px,高${Math.round(height)}px`); }
代码说明
mousedown事件:通过鼠标位置判断是否点击到div的右下角调整手柄,若是则标记isResizing为true,表示进入调整状态。- 监听
window的mouseup而非div本身:避免用户调整时将鼠标移出div区域再抬起,导致无法捕获结束事件。 - 鼠标抬起时,若之前处于调整状态,则重置标记并触发目标函数。
内容的提问来源于stack exchange,提问作者cak3_lover
相关产品推荐
相关产品推荐

