ajax及查询字符串的封装
/* ajax下载数据: method url data */ function $ajax({method = "get", url, data,success,error}){ //1、创建ajax对象 var xhr = null; try{ xhr = new XMLHttpRequest(); }catch(error){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } //判断如果数据存在 if(data){ data = querystring(data); } if(method == "get" && data){ url += "?" + data; } xhr.open(method, url, true); if(method == "get"){ xhr.send(); }else{ //必须在send方法之前,去设置请求的格式 xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); xhr.send(data); } //4、等待数据响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ //判断本次下载的状态码都是多少 if(xhr.status == 200){ if(success){ // 获取请求头中的属性 var type = xhr.getResponseHeader('Content-Type') // 是否为json if(type.indexOf('json') != -1){ success(JSON.parse(xhr.responseText)); } // 是否为xml else if(type.indexOf('xml') != -1){ success(xhr.responseXML); } // 普通字符串 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); }
按需加载
//传入calllBack时,要用一层函数包裹,要不然系统会报错... is not function function demandLoadingScript(url, callBack) { let script = document.createElement('script') if(script.readyState) {//兼容ie script.onreadystatechange = function() { if(script.readyState == 'complete' || script.readyState == 'loaded') { callBack() } } }else {//其他浏览器 script.onload = function() { callBack() } } //写在这里是为了避免程序执行之前readyState状态就已经变成了complete, //然后就不会去调用onreadystatechange了 script.src = url script.body.appendChild(script) }
自定义时间
//自定义时间 function showTime(){ var d = new Date() 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 + "年" + month + "月" + date +"日 星期" + week + " " + hour + "时" + min + "分" + sec + "秒"; } function changesize(num){ var arr = ["日", "一", "二", "三", "四", "五", "六"]; return arr[num]; } function dounbleNum(num){ if(num >=0 && num <=9){ return "0" + num; }else{ return num; } }
完美运动(包含了颜色变化,一系列运动...
//完美运动 function startMove(node, cssObj, complete){//complete = show; clearInterval(node.timer); node.timer = setInterval(function(){ var isEnd = true; //假设所有的动画都到达目的值。 for(var attr in cssObj){ var iTarget = cssObj[attr]; //计算速度 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); } //获取当前有效样式浏览器兼容的写法 function getStyle(node, cssStr){ return node.currentStyle ? node.currentStyle[cssStr] : getComputedStyle(node)[cssStr]; }
类型判断
function type(target) { // 保存引用类型和基本包装类型的情况 let temp = { "[object Object]": 'object', "[object Array]": 'array', "[object String]": 'string - object', "[object Number]": 'number - object', "[object Boolean]": 'boolean - object' } // 判断传入的是否为空 if(target === null) { return null }else if((typeof target) === 'object') { let str = Object.prototype.toString.call(target) return temp[str] }else { return typeof target } }
数组去重
// 利用对象属性吗名不能重复的特点 function unique(arr) { let obj = {} let arr1 = [] for(let key of arr) { if(!obj[key]) { // 这里可以等于任何非假的值,不要写key, key有可能是0,if判断是假的,会出问题 obj[key] = "zh" arr1.push(key) } } return arr1 }
不用node.children属性,自己封装一个获取所有子元素节点的函数
function myChild(parentElem) { // 先获取该节点的所有子节点(包括文本节点,注释节点) let elem = parentElem.childNodes let elemChild = [] for(let index in elem) { if(elem[index].nodeType === 1) { elemChild.push(elem[index]) } } return elemChild }
获取滚动条滚动的位置
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 } } }
获取可视窗口的高度和宽度
// 获取可视窗口的高度和宽度 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 } } } }
添加事件和移除事件
/** * * @param {*} node * @param {string} type * @param {*} funName */ // 兼容IE8以上,及主流浏览器 function addEvent(node,type,funName){ if(node.addEventListener){ node.addEventListener(type,funName,false); }else{ // 兼容IE8以下 node.attachEvent("on" + type,function(){ funName.call(node); }) } } // 移除事件 function removeEvent(node,type,funName){ if(node.removeEventListener){ node.removeEventListener(type,funName,false); }else{ // 兼容IE8以下 node.detachEvent("on" + type,funName); } }
获取子元素距离视口的宽高
/** * * @param {node} obj */ // 获取子元素到达页面的left值 function getCurrentLeft(obj){ var currentLeft = obj.offsetLeft; var parent = obj.offsetParent; while( parent != null){ currentLeft += parent.offsetLeft + parent.clientLeft; parent = parent.offsetParent; } return currentLeft; } // 获取子元素到达页面顶端的值 function getCurrentTop(obj){ var currentTop = obj.offsetTop; var parent = obj.offsetParent; while( parent != null){ currentTop += parent.offsetTop + parent.clientTop; parent = parent.offsetParent; } return currentTop; }
拖拽并防止出界
//拖拽并且限制出界 function limitDrag(node){ node.onmousedown = function(ev){ var e = ev || window.event; //记录鼠标和被拖拽物体相对位置 var offsetX = e.clientX - node.offsetLeft; var offsetY = e.clientY - node.offsetTop; //被拖拽物体保持相对距离和鼠标移动 document.onmousemove = function(ev){ var e = ev || window.event; var l = e.clientX - offsetX; var t = e.clientY - offsetY; //限制出界 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'; } } //取消拖拽 document.onmouseup = function(){ document.onmousemove = null; } }
阻止事件冒泡
function stopBubble(event) { if(event.stopPropagation) { event.stopPropagation() }else { event.cancelBubble = true } }
阻止默认行为
// 阻止默认行为 function cancelHandler(event) { if(event.preventDefault) { event.preventDefault() }else { event.returnValue = false } }