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

如何使用jQuery实现高度值与vw单位数值叠加后设置元素高度

需求实现可行性说明

可以实现,你现有代码存在两处错误:

  • 逻辑符号错误:需求为高度相加,你的代码中使用了减法运算符-
  • 单位运算错误:$('.content').height()返回的是纯数字格式的像素值,直接和字符串类型的'27vw'做算术运算会得到非法值,无法正常设置高度

正确JS实现方案

vw单位等价于1%的视窗宽度,我们可以先将27vw换算为对应像素值,再和.content的高度相加后赋值给.container:

// 获取.content的像素高度
let contentHeight = $('.content').height();
// 计算27vw对应的像素值
let vw27Val = window.innerWidth * 0.27;
// 赋值给.container
$('.container').css('height', contentHeight + vw27Val + 'px');

如果需要在窗口尺寸变化时自动更新高度,可添加resize监听:

function updateContainerHeight() {
  let contentHeight = $('.content').height();
  let vw27Val = window.innerWidth * 0.27;
  $('.container').css('height', `${contentHeight + vw27Val}px`);
}
// 初始化执行
updateContainerHeight();
// 窗口resize时重新计算
$(window).resize(updateContainerHeight);

纯CSS替代方案

如果.content是.container的直接子元素,无需JS也可以实现同等效果,性能更高:

.container {
  height: fit-content;
  padding-bottom: 27vw;
  box-sizing: border-box;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:54:05