56个JavaScript 实用工具函数(下)

简介: 56个JavaScript 实用工具函数

浏览器操作



(1)滚动到页面顶部


export const scrollToTop = () => {
  const height = document.documentElement.scrollTop || document.body.scrollTop;
  if (height > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, height - height / 8);
  }
}


(2)滚动到页面底部


export const scrollToBottom = () => {
  window.scrollTo(0, document.documentElement.clientHeight);  
}


(3)滚动到指定元素区域


export const smoothScroll = (element) => {
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};


(4)获取可视窗口高


export const getPageViewWidth = () => {
    return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}


(5)获取可视窗口宽度


export const getPageViewWidth = () => {
    return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}


(6)打开浏览器全屏


export const toFullScreen = () => {
    let element = document.body;
    if (element.requestFullscreen) {
      element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen()
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen()
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullScreen()
    }
}


(7)退出浏览器全屏


export const exitFullscreen = () => {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    }
}


时间操作



(1)当前时间


export const nowTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const date = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate());
    const hour = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours());
    const miu = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes());
    const sec = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds());
    return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec;
}


(2)格式化时间

export const dateFormater = (formater, time) => {
    let date = time ? new Date(time) : new Date(),
        Y = date.getFullYear() + '',
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g, Y)
        .replace(/YY|yy/g, Y.substr(2, 2))
        .replace(/MM/g,(M<10 ? '0' : '') + M)
        .replace(/DD/g,(D<10 ? '0' : '') + D)
        .replace(/HH|hh/g,(H<10 ? '0' : '') + H)
        .replace(/mm/g,(m<10 ? '0' : '') + m)
        .replace(/ss/g,(s<10 ? '0' : '') + s)
}
// dateFormater('YYYY-MM-DD HH:mm:ss')
// dateFormater('YYYYMMDDHHmmss')


JavaScript操作



(1)阻止冒泡事件


export const stopPropagation = (e) => { 
    e = e || window.event; 
    if(e.stopPropagation) {    // W3C阻止冒泡方法 
        e.stopPropagation(); 
    } else { 
        e.cancelBubble = true; // IE阻止冒泡方法 
    } 
}


(2)防抖函数


export const debounce = (fn, wait) => {
  let timer = null;
  return function() {
    let context = this,
        args = arguments;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, wait);
  };
}


(3)节流函数


export const throttle = (fn, delay) => {
  let curTime = Date.now();
  return function() {
    let context = this,
        args = arguments,
        nowTime = Date.now();
    if (nowTime - curTime >= delay) {
      curTime = Date.now();
      return fn.apply(context, args);
    }
  };
}


(4)数据类型判断


export const getType = (value) => {
  if (value === null) {
    return value + "";
  }
  // 判断数据是引用类型的情况
  if (typeof value === "object") {
    let valueClass = Object.prototype.toString.call(value),
      type = valueClass.split(" ")[1].split("");
    type.pop();
    return type.join("").toLowerCase();
  } else {
    // 判断数据是基本数据类型的情况和函数的情况
    return typeof value;
  }
}


(5)对象深拷贝


export const deepClone = (obj, hash = new WeakMap()) => {
  // 日期对象直接返回一个新的日期对象
  if (obj instanceof Date){
    return new Date(obj);
  } 
  //正则对象直接返回一个新的正则对象     
  if (obj instanceof RegExp){
    return new RegExp(obj);     
  }
  //如果循环引用,就用 weakMap 来解决
  if (hash.has(obj)){
    return hash.get(obj);
  }
  // 获取对象所有自身属性的描述
  let allDesc = Object.getOwnPropertyDescriptors(obj);
  // 遍历传入参数所有键的特性
  let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc)
  hash.set(obj, cloneObj)
  for (let key of Reflect.ownKeys(obj)) { 
    if(typeof obj[key] === 'object' && obj[key] !== null){
      cloneObj[key] = deepClone(obj[key], hash);
    } else {
      cloneObj[key] = obj[key];
    }
  }
  return cloneObj
}


相关文章
|
4天前
|
JavaScript 前端开发
JavaScript基础&实战(4)js中的对象、函数、全局作用域和局部作用域
这篇文章介绍了JavaScript中对象的基本概念和操作,包括对象属性和方法的使用、对象字面量的创建、函数的定义和作用域的概念,以及全局作用域和局部作用域的区别和特性。
JavaScript基础&实战(4)js中的对象、函数、全局作用域和局部作用域
|
4天前
|
JavaScript
js中有哪些函数?
js中有哪些函数?
5 0
|
4天前
|
JavaScript 前端开发 Java
JavaScript 特殊函数
JavaScript 特殊函数
6 0
|
4天前
|
JavaScript 前端开发
JavaScript 函数中break,continue,return 的区别
JavaScript 函数中break,continue,return 的区别
11 0
|
4天前
|
JavaScript 前端开发
JS - 立即执行函数
这篇文章解释了JavaScript中的立即执行函数(IIFE,Immediately Invoked Function Expression)的概念和用法,它用于创建局部作用域以避免全局变量的污染。文中提供了多种立即执行函数的示例,展示了如何通过不同的语法结构立即调用函数。
10 0
|
7天前
|
JavaScript 前端开发
JavaScript——实现compose函数
JavaScript——实现compose函数
13 0
|
7天前
|
JavaScript 前端开发
JavaScript——实现一些常用函数
JavaScript——实现一些常用函数
8 0
|
7天前
|
JavaScript
Vue——使用JS文件中的函数ESLint报错未定义
Vue——使用JS文件中的函数ESLint报错未定义
17 0
|
7天前
|
存储 JavaScript 前端开发
js之函数区别
js之函数区别
13 0
|
7天前
|
存储 JavaScript 索引
js arguments 的使用与自执行函数
js arguments 的使用与自执行函数
9 0