前端常用方法

118 阅读1分钟

时间戳转换成2022-10-10 10:00:00

export const getMyDate = (str) => {
  const oDate = new Date(str);
  // eslint-disable-next-line max-len
  return `${oDate.getFullYear()}-${addZero(oDate.getMonth() + 1)}-${addZero(oDate.getDate())} ${addZero(oDate.getHours())}:${addZero(oDate.getMinutes())}:${addZero(oDate.getSeconds())}`;
};

export const addZero = (num) => {
  if (parseInt(num, 10) < 10) {
    return `0${num}`;
  } else {
    return num;
  }
};

英文特殊符号转义('"[等)

export const htmlDecodeByReg = (str) => {
  let s = '';
  if (str.length === 0) return '';
  s = str.replace(/&amp;/g, '&');
  s = s.replace(/&lt;/g, '<');
  s = s.replace(/&gt;/g, '>');
  s = s.replace(/&nbsp;/g, ' ');
  s = s.replace(/&#39;/g, "'");
  s = s.replace(/&quot;/g, '"');
  return s;
};

监听URL改变

 useEffect(() => {
    const unlisten = history.listen((historyLocation) => {
      // 业务代码
      console.log(historyLocation);
    });
    return () => {
      unlisten();
    };
  }, [history]);

无痕浏览下浏览器URL hash值丢失 解决办法

// 路由文件
const { hash } = location; 
const url = window.location.href; 
if (!hash) {
    const urlParams = new URLSearchParams(location.search); 
    const router = urlParams.get('router'); // 增加一个路由hash参数
    if (router) { 
        window.open(`${url}#/${router}`, '_self'); 
    } else { 
        return <NotFound />; 
    } 
}

CST格式转成GMT格式时间

js接收java后台的时间数据时,时间格式的CST时间,而js默认的是GMT时间格式,js 需要对这个时间进行处理才能使用
由于CST转成GMT时间存在new Date()导致原时间会加14h,所以在设置时间的时候,进行了转换-14h.
方法一:减去多余的时间
const time = "Mon Jan 16 15:52:23 CST 2023";  // 后端返回的CST时间格式
const date = new Date(time); // Tue Jan 17 2023 05:52:23 GMT+0800 (中国标准时间) new Date()导致原时间会加14h
const _time = date.setHours(date.getHours()-14);  // 1673855543000 时间戳
const _date = new Date(_time); Mon Jan 16 2023 15:52:23 GMT+0800 (中国标准时间)

方法二:拼接字符串
function dateCSTToGMT(sDate){
  const dateS = sDate.split(" ");
  const strGMT = dateS[0]+" "+dateS[1]+" "+dateS[2]+" "+dateS[5]+" "+dateS[3]+" GMT+0800";
  const date = new Date(Date.parse(strGMT));
  return date;
}

js将数组分割成每n个一组

function spArr(arr, num) { //arr是你要分割的数组,num是以几个为一组
    let newArr = []  //首先创建一个新的空数组。用来存放分割好的数组
    for (let i = 0; i < arr.length;) {  //注意:这里与for循环不太一样的是,没有i++
            newArr.push(arr.slice(i, i += num));
    }
    return newArr
}

监听页面滚动 添加固定在顶部的阴影

import jsonp from 'jsonp';
componentDidMount() {
    window.addEventListener('scroll', this.handleScroll, true);
    // 发送jsonp请求
    jsonp(
      'https://...',
      {
        name: 'successCallback',
      },
      (err, data) => {
        if (err) {
          console.error('err', err.message);
        } else {
          // console.log('data', data);
          this.setState({
            solutionData: data || [],
          });
          window.localStorage.setItem('gdt-solutions', JSON.stringify(data || []));
        }
      },
    );
  }
componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll, true);
}
handleScroll(event) {
    const t = document.documentElement.scrollTop; // 目前监听的是整个body的滚动条距离
    if (t > 0) {
        document.getElementById('fixTop').classList.add('navActive');
    } else {
        document.getElementById('fixTop').classList.remove('navActive');
    }
}

.navActive {
  box-shadow: 0 2px 10px rgb(159 177 200 / 16%) !important;
}

内层div设绝对定位后外层div高度塌陷问题解决

1.外层div设置固定高度(缺点:高度不能自适应)
2.页面加载前把内层元素高度给外层元素

useEffect(() => {
    const box = document.getElementById('inner_box').offsetHeight;
    document.getElementById('out_box').style.height = `${box}px`;
  }, []);