自己写的一些没什么用的方法

62 阅读1分钟

1. 根据传入的时间,计算当天是该年的第几周

/**
  * @desc 获取每一天是本年的第几周
  * @param {*} 日期
  */ 
function getWeekOfYear(year, month, day) {
    let m = month - 1; // 月份要-1 
    let a = new Date(year, 0, 1); // 获取第一周的周一 
    a = a - 3600 * 24 * 1000 * a.getDay();
    let b = new Date(year, m, day).getTime(); // 计算 
    let c = Math.floor((b - a) / (3600 * 24 * 1000 * 7)); 
    console.log(c + 1) 
    // 第一周是0 所以要+1 
    return (c + 1)
}

2. 根据传入的时间,计算当天的开始时间戳和结束时间戳

/**
  * @desc 当天开始的时间戳和结束的时间戳
  * @param {*} timestamp 时间戳
  */ 
function getStartTimestamp (timestamp = Date.now()) {
    // 当天开始的时间戳
    const startTimestamp = new Date(new Date(timestamp).setHours(0, 0, 0, 0)).getTime();
    // 当天结束的时间戳
    const endTimestamp = new Date(new Date(timestamp).setHours(23, 59, 59, 999)).getTime();
    return {startTimestamp, endTimestamp};
}
    

3. 使页面滚动到指定节点的位置

/**
 * @description 使页面滚动到节点所在的位置 Y 轴
 * @param { HTMLElement } el 需要滚动到指定位置的节点
 * @param { HTMLElement } scrollEl 滚动容器的EL
 * @param { Number } offsetTop 距离屏幕顶部的距离
 */
export function scrollToElementLocation(el, scrollEl, offsetTop = 300) {
  // 元素距窗口顶部的距离
  const elOffsetTop = el.getBoundingClientRect().top;
  // 容器已经滚动的高度
  const  containerScrollHeight = scrollEl.scrollTop;
  // 需要滚动的高度
  const scrollHeight = containerScrollHeight + elOffsetTop - offsetTop;
  scrollEl.scrollTo({
    let: 0,
    top: scrollHeight,
    behavior: "smooth",
  })
}