TypeScript 获取元素高度

以下是使用 TypeScript 获取元素高度的完整示例代码:

typescript

复制

下载

// 获取按钮元素(明确指定为 HTMLButtonElement 类型)
const button = document.querySelector('button') as HTMLButtonElement | null;

if (!button) {
  throw new Error('未找到按钮元素');
}

// 1. 使用 offsetHeight 获取可视高度(包含边框和内边距)
const offsetHeight: number = button.offsetHeight;
console.log('offsetHeight:', offsetHeight, 'px');

// 2. 使用 clientHeight 获取内部高度(仅内容+内边距)
const clientHeight: number = button.clientHeight;
console.log('clientHeight:', clientHeight, 'px');

// 3. 使用 getBoundingClientRect() 获取精确高度(包含边框)
const rect: DOMRect = button.getBoundingClientRect();
const boundingHeight: number = rect.height;
console.log('boundingClientRect height:', boundingHeight.toFixed(2), 'px');

// 4. 使用 getComputedStyle 获取CSS定义的高度
const computedStyle: CSSStyleDeclaration = window.getComputedStyle(button);
const cssHeight: string = computedStyle.height;
console.log('CSS computed height:', cssHeight);

// 5. 获取滚动内容总高度
const scrollHeight: number = button.scrollHeight;
console.log('scrollHeight:', scrollHeight, 'px');

// 实用函数:获取元素实际渲染高度
function getActualHeight(element: HTMLElement): number {
  // 优先使用精确测量
  const rect = element.getBoundingClientRect();
  if (rect.height > 0) return rect.height;
  
  // 回退到 offsetHeight
  return element.offsetHeight;
}

// 使用实用函数
const actualHeight: number = getActualHeight(button);
console.log('实际渲染高度:', actualHeight, 'px');

// 处理元素隐藏的情况
function getHeightWithVisibility(element: HTMLElement): number | null {
  if (element.offsetParent === null) {
    console.warn('元素当前不可见');
    return null;
  }
  return getActualHeight(element);
}

// 响应式示例:在窗口大小变化时重新获取高度
window.addEventListener('resize', () => {
  const newHeight = getActualHeight(button);
  console.log('窗口调整后高度:', newHeight, 'px');
});

// 异步获取高度(确保元素已渲染)
function getHeightAfterRender(element: HTMLElement): Promise<number> {
  return new Promise(resolve => {
    if (element.offsetHeight > 0) {
      resolve(getActualHeight(element));
    } else {
      // 等待下一帧渲染
      requestAnimationFrame(() => {
        resolve(getHeightAfterRender(element));
      });
    }
  });
}

// 使用异步方法
getHeightAfterRender(button).then(height => {
  console.log('异步获取的高度:', height, 'px');
});

关键点说明:

  1. 类型断言

    typescript

    复制

    下载

    const button = document.querySelector('button') as HTMLButtonElement | null;
    • 使用类型断言确保 TypeScript 知道我们获取的是按钮元素

    • 添加 | null 处理未找到元素的情况

  2. 安全检查

    typescript

    复制

    下载

    if (!button) {
      throw new Error('未找到按钮元素');
    }
    • 确保元素存在后再进行操作

  3. 多种高度获取方法

    • offsetHeight: 最常用的可视高度

    • clientHeight: 内部内容区域高度

    • getBoundingClientRect(): 最精确的尺寸测量

    • scrollHeight: 包含滚动内容的总高度

    • getComputedStyle(): 获取 CSS 原始值

  4. 实用函数

    typescript

    复制

    下载

    function getActualHeight(element: HTMLElement): number {
      const rect = element.getBoundingClientRect();
      if (rect.height > 0) return rect.height;
      return element.offsetHeight;
    }
    • 优先使用精确测量,提供回退方案

  5. 处理特殊情况

    • 隐藏元素检测:使用 offsetParent 判断元素是否可见

    • 异步获取:使用 requestAnimationFrame 确保元素已渲染

    • 响应式处理:监听 resize 事件处理尺寸变化

运行说明:

  1. 在 HTML 中添加一个按钮:

html

复制

下载

运行

<button id="myBtn" style="padding: 10px; border: 2px solid #333; margin: 20px;">
  测试按钮
</button>
  1. 将 TypeScript 代码编译为 JavaScript:

bash

复制

下载

tsc yourfile.ts
  1. 在页面加载后执行脚本

输出示例:

text

复制

下载

offsetHeight: 44 px
clientHeight: 40 px
boundingClientRect height: 44.50 px
CSS computed height: auto
scrollHeight: 40 px
实际渲染高度: 44.50 px
异步获取的高度: 44.50 px

最佳实践建议:

  1. 首选方法

    typescript

    复制

    下载

    // 大多数场景使用这个
    const height = element.getBoundingClientRect().height;
  2. 处理小数像素值

    typescript

    复制

    下载

    // 四舍五入到整数
    const roundedHeight = Math.round(element.getBoundingClientRect().height);
  3. 性能优化

    typescript

    复制

    下载

    // 缓存测量结果
    let cachedHeight = 0;
    
    function updateHeight() {
      cachedHeight = button.getBoundingClientRect().height;
    }
    
    // 只在需要时更新
    window.addEventListener('resize', updateHeight);
  4. 框架中使用(如 React):

    typescript

    复制

    下载

    // 使用 ref 获取元素
    const buttonRef = useRef<HTMLButtonElement>(null);
    
    useEffect(() => {
      if (buttonRef.current) {
        const height = buttonRef.current.getBoundingClientRect().height;
        console.log('按钮高度:', height);
      }
    }, []);

这些方法覆盖了各种使用场景,并提供了 TypeScript 的类型安全实现。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值