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

使用$(document).height()设置背景高度时每次点击背景高度都会增加的原因?

问题原因

你在操作的.bg默认属于普通文档流内元素,你给它设置的高度会被纳入$(document).height()的统计范围,导致每次执行setDocumentHeight时都会出现如下循环:

  • 读取当前document高度
  • 将高度赋值给.bg
  • .bg的高度撑开document,使其总高度变大
  • 下一次点击取值时拿到的是更大的高度,赋值后继续撑开,就出现了高度不断增加的问题

解决方案

方案1:让.bg脱离文档流(推荐,适配背景元素的使用场景)

给.bg添加CSS定位规则,让它的高度不影响文档总高度:

.bg {
  /* fixed定位会让元素相对于视口固定,高度不会撑开文档 */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
}

方案2:缓存初始文档高度,避免重复读取变化后的高度

如果不需要动态适配文档高度变化,可以初始化时只读取一次高度:

// 初始化时读取一次高度缓存,后续复用该值
const initDocHeight = $(document).height();
function setDocumentHeight(){
  console.log("Document Height " + initDocHeight);
  $(".bg").css({"height": initDocHeight});
}
setDocumentHeight();
  
$(document).click(function(e) {
  if (e.button == 0) { setDocumentHeight(); }
});

方案3:纯CSS实现背景铺满,无需JS控制

如果只是需要背景元素铺满页面,完全可以不用JS实现:

/* 铺满整个视口且固定 */
.bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-size: cover;
  background-position: center;
}

/* 或者跟随文档高度铺满,不固定 */
.bg {
  min-height: 100vh;
  box-sizing: border-box;
  background-size: cover;
  background-position: center;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:48:01