废话不多说直接上代码:
HTML
<div class="parent">
<div class="child"></div>
</div>
CSS
// 父级元素
.parent {
position: relative;
width: 100px;
height: 100px;
border: 10px solid red;
cursor: pointer;
}
.parent:hover {
cursor: nwse-resize;
}
// 子级元素
.child {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: #000;
}
通过给子元素设置
position: absolute
四边(top
,left
,bottom
,right
)设置为0 使其自适应撑起内容区域
可以看出来,我并没有给子元素设置宽高,但确实占满看父级内容区。为了验证这个想法,我写了一个拖拽边框放大事件,代码如下
JavaScript
const parent = document.querySelector('.parent');
let isResizing = false;
let startX, startY, startWidth, startHeight;
parent.addEventListener('mousedown', (e) => {
isResizing = true;
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(parent).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(parent).height, 10);
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
});
function resize(e) {
if (!isResizing) return;
const newWidth = startWidth + (e.clientX - startX);
const newHeight = startHeight + (e.clientY - startY);
parent.style.width = `${newWidth}px`;
parent.style.height = `${newHeight}px`;
}
function stopResize() {
isResizing = false;
document.removeEventListener('mousemove', resize);
document.removeEventListener('mouseup', stopResize);
}