一、元素查找
//1.Node节点
document.getElementById(id);
document.querySelector(selector);
document.doctype;
document.documentElement;
document.head;
document.title;
document.body;
//2.NodeList,节点数组
document.getElementsByName(name);
document.getElementsByTagName(name);
document.getElementsByClassName(name);
document.querySelectorAll(selector);
document.links;
document.scripts;
document.images;
document.embeds;
document.forms;
document.all;
//add class
el.className += ""+className;
//ie10+
el.classList.add(className);
//has class
function hasClass(el,className){
return new RegExp('(^| )' + className + '( |$)','gi').test(el.className);
}
//ie10+
el.classList.contains(className);
//toggle class
function toggleClass(el.className){
var classes = el.className.split(' ');
var existingIndex = -1;
for (var i = classes.length; i--) {
if(classes[i] === className){
existingIndex = i;
}
}
if(existingIndex >= 0){
classes.splice(existingIndex,1);
}else{
classes.push(className);
}
el.className = classes.join(' ');
}
//ie10+
el.classList.toggle(className);
//remove class
function removeClass(el,className){
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(" ").join('|') + '(\\b|$)','gi'),' ');
}
//ie10+
el.classList.remove(className);
//创建
var el = document.createElement(name);
//复制
el.cloneNode(true);//默认为false(克隆节点及其后代,true(克隆节点及其属性,以及后代))
//向节点添加最后一个子节点
parent.appendChild(el);
//在指定节点之前插入新的子节点
parent.insertBefore(el,parent.childNodes[0]);
//insertAdjacentHTML方法
el.insertAdjacentHTML(where,htmlString);
el.insertAdjacentHTML('beforeBegin',htmlString);//在该元素前插入
el.insertAdjacentHTML('afterBegin',htmlString);//在该元素第一个子元素前插入
el.insertAdjacentHTML('beforeEnd',htmlString);//在该元素最后一个子元素后面插入
el.insertAdjacentHTML('afterEnd',htmlString);//在该元素后面插入
//父元素
el.parentNode;
//删除节点
el.parentNode.removeChild(el);
//兄弟节点 ie9+
var siblings = Array.prototype.filter.call(el.parentNode.children,function(child){
return child !== el;
});
//下一个兄弟节点
//ie8+
function nextElementSibling(el){
do { el = el.nextSibling; } while ( el && el.nodeType !== 1 );
return el;
}
//ie9+
el.nextElementSibling;
//上一个兄弟节点
//ie8
function previousElementSibling(el){
do{
el = el.previousSibling;
}while( el && el.nodeType !== 1 );
return el;
}
//ie9+
el.prviousElementSibling;
//children
//ie8
var children = [];
for(var i = el.children.length; i--){
if(el.children[i].nodeType != 8){
children.unshift(el.children[i]);
}
}
//ie9+
el.children;
//获取属性
el.getAttribute('alt');
//设置属性
el.setAttribute('alt','图片描述');
//获取元素内容
el.innerHTML;
//设置元素内容
el.innerHTML = string;
//获取元素内容(包含元素本身)
el.outerHTML;
//设置元素内容(包含元素本身)
el.outerHTML = string;
//获取文本内容
//ie8
el.innerText;
//ie9+
el.textContent;
//文本设置文本内容
//ie8
el.innerText = string;
//ie9+
el.textContent = string;
//获取css样式
//ie8
el.currentStyle[attrName];
//ie9+
window.getComputedStyle(el)[attrName];
//伪类
window.getComputedStyle(el,":after")[attrName];
//设置css样式
el.style.display = 'none';
七、位置大小
getBoundingClientRect //返回一个对象,包含top,left,right,bottom,width,height
//元素在页面上的偏移量
var rect = el.getBoundingClientRect()
return{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
//元素自身宽高(包含border,padding)
el.offsetWidth;
el.offsetHeight;
//带垂直滚动条的页面总高度
document.documentElement.scrollHeight;
//在没有滚动条的情况下,元素内容总高度和宽度
scrollHeight,scrollWidth;
//视口大小
//ie9+
var pageWidth = window.innerWidth,pageHeight = window.innerHeight;
//ie8以下
if(typeof pageWidth != "number"){
//ie8
if(document.compatMode == "CSS1Compat"){
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
}else{
//ie6
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}
//绑定事件
//ie9+
el.addEventListener(eventName,handler,Booleans);//Booleans默认为false(事件在冒泡阶段执行),true(事件在捕获阶段执行)
//ie8
el.attachEvent('on' + eventName,function(){
handler.call(el);
});
//移除事件
//ie9+
el.removeEventListener(eventName,handler);
//ie8
el.detachEvent('on'+eventName,handler);
//事件触发
if(document.createEvent){
//ie9+
var event = document.createEvent('HTMLEvents');
event.initEvent('change',true,false);
el.dispatchEvent(event);
}else{
//ie8
el.fireEvent('onchange');
}
//event对象
var event = window.event || event;
//事件的目标节点
var target = event.target || event.srcElement;
//事件代理
ul.addEventListener('click',function(event){
if(event.target.tagName.toLowerCase() === 'li'){
console.log(event.target.innerHTML);
}
})
九、DOM加载完毕
function ready(fn){
if(document.readyState != 'loading'){
//ie9+
document.addEventListener('DOMContentLoaded',fn);
}else{
//ie8
document.attachEvent("onreadystatechange",function(){
if(document.readyState != 'loading'){
fn();
}
})
}
}
十、绑定上下文
//ie8
fn.apply(context,arguments);
//ie9+
fn.bind(context);
十一、去除前后空格
//ie8
string.replace(/^\s+|\s+$/g,'');
//ie9+
string.trim();
//GET
var request = new XMLHttpRequest();
request.open('GET','user.php?name=wushaoxiong&sex=boy',true);//false(同步)
request.send();
//ie8
request.onreadystatechange = function(){
if(this.readyState === 4){
if(this.status >= 200 && this.status < 400){
var data = JSON.parse(this.responseText);
}else{
//报错
}
}
}
//ie9+
request.onload = function(){
if(request.status >= 200 && request.status < 400){
var data = JSON.parse(request.responseText);
}else{
//服务器返回出错
}
}
request.onerror = function(){
//连接错误
}
//POST
var request = new XMLHttpRequest();
request.open('POST','user.php',true);
request.setRequestHeader('Content-type','application/x-www-form-urlencoded');
request.send(dataString);
十三、节点遍历
function forEach(nodeList,callback){
if(Array.prototype.forEach){
//ie9+
Array.prototype.forEach.call(nodeList,callback);
}else{
//ie8
for(var i = 0; i < nodeList.length; i++){
callback(nodeList[i],i);
}
}
}
十四、从数组中获取随机成员
var items = [1,2,3,4,5,6,7,8,9,0];
var randomItem = items[Math.floor(Math.random()*items.length)];
十五、获取指定范围内的随机数
function random(max,min){
return Math.floor(Math.random()*(max-min+1))+min;
}
十六、生成从min到max的数字数组
function numArr(max,min){
var arr = [];
for(var i = min+1; arr.push(i++) < max;)
}
十七、生成长度为len的随机字符串
function randAlphaNum(len){
var str = '';
for(str.length < len; str += Math.random().toString(36).substr(2));
return str.substr(0,len);
}
十八、打乱数组的排序
function disArr(arr){
arr = arr.sort(function(){
return Math.random() - 0.5;
})
}
十九、数组追加到另一个数组
function pushArr(arr1,arr2){
Array.prototype.push.apply(arr1,arr2);
}
二十、参数转换成数组
function objToArr(obj){
var arr = Array.prototype.slice.call(obj);
}
二十一、验证是否是数字
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
二十二、验证是否是数组
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]';
}
二十三、获取数组中最大值和最小值
function inNum(arr){
return maxNum = Math.max.apply(Math,arr);
// retyrn minNum = Math.min.apply(Math,arr);
}
二十四、截断数组
function cutArr(arr,len){
arr.length = len;
}
二十五、在条件中使用逻辑与或
function ifDo(foo,callback){
foo==10 && callback(); //相当于if(foo == 10){callback()}
foo == 10 || callback(); //if(foo != 10){callback()}
}
二十六、使用map()方法对数组循环
function forMap(arr){
arr.map(function(item){
return item;
})
}
二十七、保留指定小数位数
function cutNum(num,len){
num = num.toFixed(len); //返回字符串
}
二十八、对象序列化(与字符串相互转换)
function objToStr(obj){
return str = JSON.stringify(obj);
//return obj = JSON.parse(str);
}