You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4中如何将可调整大小的div宽度读取到变量中

获取CSS resize调整后的div宽度

当然有可行的方案!这里给你几种实用的实现方式,适配不同的浏览器场景:

方式1:使用Element Resize Observer API(推荐)

这是现代浏览器原生支持的专门监听元素尺寸变化的API,相比传统方法更高效、精准,能实时捕捉到div调整后的尺寸变化。

示例代码:

<html>
<head>
<style>
div {
    border: 2px solid;
    padding: 20px;
    width: 300px;
    resize: horizontal;
    overflow: auto;
}
</style>
</head>
<body>
<p><b>Note:</b> Internet Explorer does not support the resize property.</p>
<div id="resizableDiv">Let the user resize both the height and the width of this div element.</div>

<script>
const resizableDiv = document.getElementById('resizableDiv');

// 创建ResizeObserver实例
const resizeObserver = new ResizeObserver(entries => {
  for (const entry of entries) {
    // 获取包含padding和border的总宽度
    const totalWidth = entry.target.offsetWidth;
    // 获取仅内容区域的宽度(不含padding、border)
    const contentWidth = entry.contentRect.width;
    
    console.log('调整后的总宽度:', totalWidth);
    console.log('内容区域宽度:', contentWidth);
  }
});

// 开始监听目标div
resizeObserver.observe(resizableDiv);
</script>
</body>
</html>

方式2:监听鼠标/触摸结束事件(兼容旧浏览器)

如果需要兼容一些不支持Resize Observer的旧浏览器,可以通过监听用户调整操作结束的事件,来获取最终的宽度:

<html>
<head>
<style>
div {
    border: 2px solid;
    padding: 20px;
    width: 300px;
    resize: horizontal;
    overflow: auto;
}
</style>
</head>
<body>
<p><b>Note:</b> Internet Explorer does not support the resize property.</p>
<div id="resizableDiv">Let the user resize both the height and the width of this div element.</div>

<script>
const resizableDiv = document.getElementById('resizableDiv');

// 鼠标调整结束后获取宽度
resizableDiv.addEventListener('mouseup', () => {
  const currentWidth = resizableDiv.offsetWidth;
  console.log('调整后的宽度:', currentWidth);
});

// 适配移动端触摸调整的场景
resizableDiv.addEventListener('touchend', () => {
  const currentWidth = resizableDiv.offsetWidth;
  console.log('调整后的宽度:', currentWidth);
});
</script>
</body>
</html>

小知识点补充

  • offsetWidth:获取元素的总宽度,包含内容、内边距(padding)、边框(border),不包含外边距(margin)和滚动条宽度
  • clientWidth:获取元素的内容+内边距宽度,不包含边框和滚动条
  • contentRect.width(Resize Observer专属):仅获取元素内容区域的宽度,不含padding、border

你可以根据自己的实际需求,选择合适的宽度属性来获取值。

内容的提问来源于stack exchange,提问作者Rama Krishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:56