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

如何获取HTML元素宽度并将像素单位转换为相对于屏幕尺寸的百分比

HTML元素像素宽度转屏幕相对百分比方案

核心计算逻辑

要转成相对于屏幕宽度的百分比,直接套用公式即可:
百分比值 = (元素像素宽度 ÷ 屏幕参考宽度) × 100
你给出的示例代入后:(683px ÷ 1366px) × 100 = 50%,和预期结果一致。

原生JS实现代码

// 可根据需求选择屏幕宽度取值:
// window.innerWidth:浏览器可视区域宽度(不含滚动条、书签栏等浏览器UI)
// screen.width:设备物理屏幕总宽度
const screenRefWidth = window.innerWidth;

// 获取目标元素
const targetEle = document.querySelector('div');

// 读取元素的像素宽度:内联样式直接取style.width,非内联样式用getComputedStyle读取实际渲染宽度
let elePixelWidth = parseFloat(targetEle.style.width);
if (isNaN(elePixelWidth)) {
  elePixelWidth = parseFloat(getComputedStyle(targetEle).width);
}

// 计算百分比,保留2位小数避免精度冗余
const percentVal = ((elePixelWidth / screenRefWidth) * 100).toFixed(2);

// 替换为百分比单位
targetEle.style.width = `${percentVal}%`;

扩展适配

如果需要窗口大小变化时自动更新百分比宽度,可以绑定resize事件:

// 先把上述计算逻辑封装为updateWidthToPercent函数
window.addEventListener('resize', () => {
  updateWidthToPercent(targetEle);
});

内容的提问来源于stack exchange,提问作者ali karamii

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:27:03