Ajax and query string encapsulation

            /* Method url data */
            function $ajax({method = "get", url, data,success,error}){
                // create an Ajax object
                var xhr = null;
                try{
                    xhr = new XMLHttpRequest();
                }catch(error){
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }

                // Determine if the data exists
                if(data){
                    data = querystring(data);
                }

                if(method == "get" && data){
                    url += "?" + data;
                }

                xhr.open(method, url, true);

                if(method == "get"){
                    xhr.send();
                }else{
                    // The request format must be set before the send method
                    xhr.setRequestHeader("content-type"."application/x-www-form-urlencoded");
                    xhr.send(data);
                }

                 //4. Wait for the data response
                   
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4) {// Determine the status code of this download
                        if(xhr.status == 200) {if(success){
                                 // Get the attributes in the request header
                                var type = xhr.getResponseHeader('Content-Type')
                                // Whether it is json
                                if(type.indexOf('json') != - 1){
                                    success(JSON.parse(xhr.responseText));
                                }
                                // Whether it is XML
                                else if(type.indexOf('xml') != - 1){
                                    success(xhr.responseXML);
                                }
                                // A common character string
                                else{ success(xhr.responseText); }}}else{
                            if(error){
                                error("Error:" + xhr.status);
                            }
                        }
                    }
                }
            }

            function querystring(obj){
                var str = "";
                for(var attr in obj){
                    str += attr + "=" + obj[attr] + "&";
                }
                return str.substring(0, str.length - 1);
            }
Copy the code

According to the need to load

// Call the calllBack with a layer of functions, otherwise the system will report an error... is not function
    function demandLoadingScript(url, callBack) {
      let script = document.createElement('script')
      if(script.readyState) {/ / compatible with ie
        script.onreadystatechange = function() {
          if(script.readyState == 'complete' || script.readyState == 'loaded') {
            callBack()
          }
        }
      }else {// Other browsers
        script.onload = function() {
          callBack()
        }
      }
      // This is to avoid readyState becoming complete before the program executes.
      // Then onreadyStatechange will not be called
      script.src = url
      script.body.appendChild(script)
    }
Copy the code

Custom time

// Customize the time
function showTime(){
    var d = new Date(a)var year = d.getFullYear();
    var month = d.getMonth() + 1;/ / 0-11
    var date = d.getDate();
    var week = d.getDay();/ / 0-9
    week = changesize(week);
    var hour = d.getHours();
    hour = dounbleNum(hour);
    var min = d.getMinutes();
    min = dounbleNum(min);
    var sec = d.getSeconds();
    sec = dounbleNum(sec);
    return year + "Year" + month + "Month" + date +"Day week" + week + "" + hour + "When" + min + "Points" + sec + "Seconds";
}
function changesize(num){
    var arr = ["Day"."一"."二"."Three"."Four"."Five"."Six"];
    return arr[num];
}
function dounbleNum(num){
    if(num >=0 && num <=9) {return "0" + num;
    }else{
        returnnum; }}Copy the code

Perfect movement (contains color changes, a series of movements…

// Perfect movement
function startMove(node, cssObj, complete){//complete = show;
    clearInterval(node.timer);
    node.timer = setInterval(function(){
        var isEnd = true; // Assume that all animations reach the destination value.
        for(var attr in cssObj){
            var iTarget = cssObj[attr];
            // Compute speed
            var iCur = null;
            if(attr == "opacity"){
                iCur = parseInt(parseFloat(getStyle(node, "opacity")) * 100);
            }else{
                iCur = parseInt(getStyle(node, attr))
            }
            
            var speed = (iTarget - iCur) / 8;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

            
            if(attr == "opacity"){
                iCur += speed;
                node.style.opacity = iCur / 100;
                node.style.filter = "alpha(opacity=" + iCur +  ")";
            }else{
                node.style[attr] = iCur + speed + 'px';
            }  

            if(iCur ! = iTarget){ isEnd =false; }}if(isEnd){
            clearInterval(node.timer);
            if(complete){ complete.call(node); }}},30);
}

// Get the browser-compatible writing of the current valid style
function getStyle(node, cssStr){
    return node.currentStyle ? node.currentStyle[cssStr] : getComputedStyle(node)[cssStr];
}
Copy the code

Type judgment

    function type(target) {
      // Save the reference type and the base wrapper type
      let temp = {
        "[object Object]": 'object'."[object Array]": 'array'."[object String]": 'string - object'."[object Number]": 'number - object'."[object Boolean]": 'boolean - object'
      }
      // Check whether the incoming is null
      if(target === null) {
        return null
      }else if((typeof target) === 'object') {
        let str = Object.prototype.toString.call(target)
        return temp[str]
      }else {
        return typeof target
      }
    }
Copy the code

Array to heavy

  // Take advantage of the fact that object names cannot be repeated
    function unique(arr) {
      let obj = {}
      let arr1 = []
      for(let key of arr) {
        if(! obj[key]) {// This can be equal to any value that is not false, don't write key, key can be 0, if the judgment is false, there will be a problem
          obj[key] = "zh"
          arr1.push(key)
        }
      }
      return arr1
    }
Copy the code

Instead of using the Node. children property, encapsulate a function that gets all the child element nodes

    function myChild(parentElem) {
    // Get all the children of this node (including text node, comment node)
    let elem = parentElem.childNodes
    let elemChild = []
    for(let index in elem) {
      if(elem[index].nodeType === 1) {
        elemChild.push(elem[index])
      }
    }
    return elemChild
   }
Copy the code

Gets the scroll bar scroll position

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

Gets the height and width of the visible window

 // Gets the height and width of the visible window
  function getViewPortOffset() {
    if(window.innerWidth) {
      return {
        h: window.innerHeight,
        w: window.innerWidth
      }
    }else {
      if(document.compatMode === "BackCompat") {
        return {
          h: document.body.clientHeight,
          w: document.body.clientWidth
        }
      }else {
        return {
          h: document.documentElement.clientHeight,
          w: document.documentElement.clientWidth
        }
      }
    }
  }
Copy the code

Add events and remove events

        /** * * @param {*} node * @param {string} type * @param {*} funName */
        // Compatible with IE8 or above, and mainstream browsers
        function addEvent(node,type,funName){
            if(node.addEventListener){
                node.addEventListener(type,funName,false);
            }else{
                // Compatible with IE8 or below
                node.attachEvent("on" + type,function(){ funName.call(node); }}})// Remove the event
        function removeEvent(node,type,funName){
            if(node.removeEventListener){
                node.removeEventListener(type,funName,false);
            }else{
                // Compatible with IE8 or below
                node.detachEvent("on"+ type,funName); }}Copy the code

Gets the width and height of the child from the viewport

            /** * * @param {node} obj */
            // Get the left value of the child element arriving on the page
            function getCurrentLeft(obj){
                var currentLeft = obj.offsetLeft;
                var parent = obj.offsetParent;
                while( parent ! =null){
                    currentLeft += parent.offsetLeft + parent.clientLeft;
                    parent = parent.offsetParent;
                }
                return currentLeft;
            }

            // Get the value of the child element to the top of the page
            function getCurrentTop(obj){
                var currentTop = obj.offsetTop;
                var parent = obj.offsetParent;
                while( parent ! =null){
                    currentTop += parent.offsetTop + parent.clientTop;
                    parent = parent.offsetParent;
                }
                return currentTop;
            }
 
Copy the code

Drag and prevent out of bounds

   // Drag and restrict out of bounds
function limitDrag(node){
    node.onmousedown = function(ev){
         var e = ev || window.event;
         // Record the position of the mouse relative to the dragged object
         var offsetX = e.clientX - node.offsetLeft;
         var offsetY = e.clientY - node.offsetTop;

        // Keep the dragged object relative distance and mouse move
         document.onmousemove = function(ev){
             var e = ev || window.event;
             var l = e.clientX - offsetX;
             var t = e.clientY - offsetY;

            // Limit out of bounds
            if(l <= 0){
                l = 0;
            }
            var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
            if(l >= windowWidth - node.offsetWidth){
                l = windowWidth - node.offsetWidth;
            }

            if(t <= 0){
                t = 0;
            }
            var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
            if(t >= windowHeight - node.offsetHeight){
                t = windowHeight - node.offsetHeight;
            }

            node.style.left = l + 'px';
            node.style.top = t + 'px'; }}// Cancel drag
     document.onmouseup = function(){
        document.onmousemove = null; }}Copy the code

Prevents events from bubbling

    function stopBubble(event) {
      if(event.stopPropagation) {
        event.stopPropagation()
      }else {
        event.cancelBubble = true}}Copy the code

Blocking default behavior

     // Prevent default behavior
    function cancelHandler(event) {
      if(event.preventDefault) {
        event.preventDefault()
      }else {
        event.returnValue = false}}Copy the code