获取文档总高度的正确方法及TypeScript无报错原因咨询
问题解答
问题1:获取文档总高度的正确方式
你当前写法错误的核心原因是:<svelte:body> 并不支持绑定 offsetHeight 和 clientHeight 属性——这两个属性不属于Svelte为 <svelte:body> 提供的可绑定API,因此会返回 undefined。
要获取文档的总高度(包含超出视口的滚动内容),需通过原生DOM API直接获取,且要确保DOM已挂载后再执行操作。示例代码如下:
<script lang="ts"> import { onMount } from 'svelte'; let docHeight: number; onMount(() => { // 兼容不同浏览器和布局,取多个高度属性的最大值 const getDocHeight = () => Math.max( document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.offsetHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.body.clientHeight ); docHeight = getDocHeight(); // 监听窗口 resize 和滚动事件,实时更新高度 const updateHeight = () => docHeight = getDocHeight(); window.addEventListener('resize', updateHeight); window.addEventListener('scroll', updateHeight); // 组件销毁时移除监听 return () => { window.removeEventListener('resize', updateHeight); window.removeEventListener('scroll', updateHeight); }; }); </script> <h1>文档总高度:{docHeight}</h1>
问题2:TypeScript未报错的原因
- Svelte绑定的类型宽松性:Svelte的类型定义中,
<svelte:body>的绑定属性没有做严格的枚举限制,允许绑定任意自定义属性,TypeScript无法在编译阶段检测到这些无效绑定。 - 类型检查模式限制:你仅对变量做了
number类型标注,但未开启strictNullChecks等严格模式。默认情况下TypeScript允许undefined赋值给number类型,不会触发报错。 - 编译阶段校验局限:Svelte的绑定逻辑是运行时处理的,编译阶段不会对绑定属性的有效性做完全校验,导致TypeScript无法提前捕获该错误。
内容的提问来源于stack exchange,提问作者SaroGFX
相关产品推荐
相关产品推荐

