常用工具Get!

1、获取元素位置

/**
 * 获取元素到网页顶部的距离
 * @param element dom对象
 */
const getElementTop = (element) => {
  let actualTop = element.offsetTop;
  let current = element.offsetParent;

  while (current !== null) {
    actualTop += current.offsetTop;
    current = current.offsetParent;
  }

  return actualTop;
};

摘自阮一峰的网络日志 > 用Javascript获取页面元素的位置

2、防抖

/**
 * 防抖
 * @param func 执行回调
 * @param time 延迟时间
 * @param immediate 要不要立即执行,默认不执行
 */
const debounce = (func, time, immediate = false) => {
  let timer: number | null = null;
  return (...args: any) => {
    if (timer) clearInterval(timer);
    if (immediate) {
      if (!timer) func.apply(this, args);
      timer = window.setTimeout(() => {
        timer = null;
      }, time);
    } else {
      timer = window.setTimeout(() => {
        func.apply(this, args);
      }, time);
    }
  };
};

3、获取窗口宽高比例

/* TypeScript */

/**
 * 获取窗口宽高
 * @param sType 选择返回数据w: 宽, h: 高, 不填: 宽高比
 */
const getClient = (sType) => {
  const getClientHeight = () => {
    let clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
      clientHeight = document.body.clientHeight < document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight;
    } else {
      clientHeight = document.body.clientHeight > document.documentElement.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    return clientHeight;
  };
  const getClientWidth = () => {
    return document.documentElement.clientWidth;
  };
  switch (sType) {
    case 'w':
      return getClientWidth();
    case 'h':
      return getClientHeight();
    default:
      return getClientWidth() / getClientHeight() > 1 ? 1 : 0;
  }
};
posted on 2022-02-28 15:15  oneMao  阅读(160)  评论(0)    收藏  举报