美文网首页前端JavaScript
常用的JavaScript方法封装

常用的JavaScript方法封装

作者: 前端陈陈陈 | 来源:发表于2022-05-12 20:03 被阅读0次

    1、获得滚动条的滚动距离

    function getScrollOffset() {
        if (window.pageXOffset) {
            return {
                x: window.pageXOffset,
                y: window.pageYOffset
            }
        } else {
            return {
                x: document.body.scrollLeft + document.documentElement.scrollLeft,
                y: document.body.scrollTop + document.documentElement.scrollTop
            }
        }
    }
    

    2、获得视口的尺寸

    function getViewportOffset() {
        if (window.innerWidth) {
            return {
                w: window.innerWidth,
                h: window.innerHeight
            }
        } else {
            // ie8及其以下
            if (document.compatMode === "BackCompat") {
                // 怪异模式
                return {
                    w: document.body.clientWidth,
                    h: document.body.clientHeight
                }
            } else {
                // 标准模式
                return {
                    w: document.documentElement.clientWidth,
                    h: document.documentElement.clientHeight
                }
            }
        }
    }
    

    3、封装自己的forEach方法

    Array.prototype.myForEach = function (func, obj) {
        var len = this.length;
        var _this = arguments[1] ? arguments[1] : window;
        // var _this=arguments[1]||window;
        for (var i = 0; i < len; i++) {
            func.call(_this, this[i], i, this)
        }
    }
    

    4、封装自己的filter方法

    Array.prototype.myFilter = function (func, obj) {
        var len = this.length;
        var arr = [];
        var _this = arguments[1] || window;
        for (var i = 0; i < len; i++) {
            func.call(_this, this[i], i, this) && arr.push(this[i]);
        }
        return arr;
    }
    

    5、数组map方法

    Array.prototype.myMap = function (func) {
        var arr = [];
        var len = this.length;
        var _this = arguments[1] || window;
        for (var i = 0; i < len; i++) {
            arr.push(func.call(_this, this[i], i, this));
        }
        return arr;
    }
    

    6、数组every方法

    Array.prototype.myEvery = function (func) {
        var flag = true;
        var len = this.length;
        var _this = arguments[1] || window;
        for (var i = 0; i < len; i++) {
            if (func.apply(_this, [this[i], i, this]) == false) {
                flag = false;
                break;
            }
        }
        return flag;
    }
    

    7、数组reduce方法

    Array.prototype.myReduce = function (func, initialValue) {
        var len = this.length,
            nextValue,
            i;
        if (!initialValue) {
            // 没有传第二个参数
            nextValue = this[0];
            i = 1;
        } else {
            // 传了第二个参数
            nextValue = initialValue;
            i = 0;
        }
        for (; i < len; i++) {
            nextValue = func(nextValue, this[i], i, this);
        }
        return nextValue;
    }
    
    

    8、设备判断:android、ios、web

    const isDevice = function() { // 判断是android还是ios还是web
      var ua = navigator.userAgent.toLowerCase()
      if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') { // ios
        return 'iOS'
      }
      if (ua.match(/Android/i) === 'android') {
        return 'Android'
      }
      return 'Web'
    }
    

    9、文本复制功能

    const copyTxt = function(text, fn) { // 复制功能
      if (typeof document.execCommand !== 'function') {
        console.log('复制失败,请长按复制')
        return
      }
      var dom = document.createElement('textarea')
      dom.value = text
      dom.setAttribute('style', 'display: block;width: 1px;height: 1px;')
      document.body.appendChild(dom)
      dom.select()
      var result = document.execCommand('copy')
      document.body.removeChild(dom)
      if (result) {
        console.log('复制成功')
        typeof fn === 'function' && fn()
        return
      }
      if (typeof document.createRange !== 'function') {
        console.log('复制失败,请长按复制')
        return
      }
      var range = document.createRange()
      var div = document.createElement('div')
      div.innerhtml = text
      div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;')
      document.body.appendChild(div)
      range.selectNode(div)
      var selection = window.getSelection()
      console.log(selection)
      if (selection.rangeCount > 0) {
        selection.removeAllRanges()
      }
      selection.addRange(range)
      document.execCommand('copy')
      typeof fn === 'function' && fn()
      console.log('复制成功')
    }
    

    10 根据url地址下载

    export const download = (url)=>{
    var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome')>-1;
    var isSafari = navigator.userAgent.toLowerCase().indexOf('safari')>-1;
    if(isChrome || isSafari){
    var link = document.createElement('a');
    link.href = url;
    if(link.download !== undefined){
    var fileName = url.substring(url.lastIndexOf('/')+1,url.length);
    link.download = fileName
    }
    if(document.createEvent){
    var e = document.createEvent('MouseEvents');
    e.initEvent('click',true,true);
    link.dispatchEvent(e);
    return true;
    }
    }
    if(url.indexOf('?')===-1){
    url+='?download'
    }
    window.open(url,'_self');
    return true;
    }
    

    11、el添加某个class

    export const addClass = (el,className)=>{
    if(hasClass(el,className)){
    return
    }
    let newClass = el.className.split(' ')
    newClass.push(className)
    el.className = newClass.join(' ')
    }
    
    

    11 、el去除某个class

    export cosnt removeClass = (el,className)=>{
    if(!hasClass(el,className)){
    return
    }
    let reg = new RegExp('(^|\\s)'+className+'(\\s|$)','g')
    el.className = el.className.replace(reg,'')
    }
    

    12 、将类数组转换为数组

    export const formArray = (ary) => { 
    var arr = [];
    if (Array.isArray(ary)) {
    arr = ary;
    } else {
    arr = Array.prototype.slice.call(ary); 
    }; 
    return arr; 
    }
    
    

    13、去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格

    export const trim = (str, type) => {
    type = type || 1 
    switch (type) { 
    case 1: 
    return str.replace(/\s+/g, "");
    case 2:
    return str.replace(/(^\s*)|(\s*$)/g, "");
    case 3:
    return str.replace(/(^\s*)/g, "");
    case 4: 
    return str.replace(/(\s*$)/g, ""); 
    default: 
    return str;
    } 
    }
    

    14、 判断两个对象是否键值相同

    export const isObjectEqual = (a, b) => { 
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b); 
    if (aProps.length !== bProps.length) {
    return false; 
    } 
    for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i]; 
    if (a[propName] !== b[propName]) {
    return false; 
    } 
    }
    return true;
    }
    

    相关文章

      网友评论

        本文标题:常用的JavaScript方法封装

        本文链接:https://www.haomeiwen.com/subject/ewjeurtx.html