1.获取非行间元素的样式
function getstyle(Obj,name){
if(Obj.currentStyle){
//ie
return Obj.currentStyle[name];
}
else{
//FF Chrome
return getCompunedStyle(Obj,false)[name];
}
}
调用方式:getstyle(obj,name)
obj:需要获取的元素对象
name:需要获取的样式名
2.数组排序(升序)
var array=[11,22,8,45,89,12]
array.sort(function(n1,n2){
return n1-n2
})
alert(array)
3.zepto封装的滑动方法
handleScrollTo : function () {
$.fn.scrollTo =function(options){
var defaults = {
toT : 0, //滚动目标位置
durTime : 400, //过渡动画时间
delay : 20, //定时器时间
callback:null //回调函数
};
var opts = $.extend(defaults,options),
timer = null,_this = this,
curTop = _this.scrollTop(),//滚动条当前的位置
subTop = opts.toT - curTop, //滚动条目标位置和当前位置的差值
index = 0,dur = Math.round(opts.durTime / opts.delay),
per = Math.round(subTop/dur),
smoothScroll = function(t){
index++;
if(index >= dur){
_this.scrollTop(t);
window.clearInterval(timer);
if(!publicFun.isNull(opts.callback) && typeof opts.callback == 'function') opts.callback();
}else{
_this.scrollTop(curTop + index*per);
}
};
timer = window.setInterval(function(){
smoothScroll(opts.toT);
}, opts.delay);
return _this;
};
},
例 :回到顶部
handleScrollTo()
$("body").scrollTo( {toT : 0} );
4.数组的随机排序
var array=[1,22,3,,14,52,8]
function shuffle(arr) {
arr.sort(function () {
return Math.random() - 0.5;
});
}
shuffle(array)
console.log(array)
5.预加载(附Html及js)
html:<div class="loading"> <div class="page"> <div class="h832" style="padding-top: 0px;"> <div class="innerDiv"> <div class="line_c"> <div class="line"></div> </div> <p>0% loading...</p> </div> </div> </div> </div> var speed=0; function preloadimages(arr){ var newimages=[], loadedimages=0; var arr=(typeof arr!="object")? [arr] : arr; function imageloadpost(){ loadedimages++; speed=parseInt(loadedimages/arr.length*100); $('.loading p').text(speed+'% loading...'); $('.line_c .line').css('left',-(100-speed)+'%'); if (loadedimages==arr.length){ $('.loading').hide(); // $('.swiper-wrapper1').show(); } } for (var i=0; i<arr.length; i++){ newimages[i]=new Image(); newimages[i].src=arr[i]; newimages[i].onload=function(){ imageloadpost(); } newimages[i].onerror=function(){ imageloadpost() } } } var imagesarray=[需要加载的数据资源]; preloadimages(imagesarray);
6.数组去重
function removeDuplicatedItem(arr) { var ret = []; for (var i = 0,i< arr.length; i++) { if (ret.indexOf(arr[i]) === -1) { ret.push(arr[i]); } } return ret; }
7.获取指定范围内的随机数
var getRandom = function(max, min) { min = arguments[1] || 0; return Math.floor(Math.random() * (max - min + 1) + min); };
8.数组去除重复字符
function arry(myArray){ var haha=myArray; for(var i=0;i<myArray.length;i++) { for(var j=0;j<myArray.length;j++) { temp=myArray[i]; if((i+j+1)<myArray.length&&temp==myArray[i+j+1]) //如果当前元素与后一个元素相等 haha.splice(i+j+1,1); //然后就移除下一个元素 } } return haha; }
9.短信发送60秒倒计时
//settime($("#getPhoneCode"),60); function settime($obj, time) { if (time == 0) { $obj.attr("disabled", false); $obj.css("background", "#f38401").css("cursor", "pointer"); $obj.text("获取手机验证码"); return; } else { $obj.attr("disabled", true); $obj.css("background", "#ccc").css("cursor", "not-allowed"); $obj.text("重新发送(" + time + ")"); time--; } setTimeout(function () { settime($obj, time) }, 1000) }
10.去除数组中的最大值和最小值
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; var maxInNumbers = Math.max.apply(Math, numbers); var minInNumbers = Math.min.apply(Math, numbers);
11.数组中找一个数
function find (x, y) { for ( let i = 0; i < x.length; i++ ) { if ( x[i] == y ) return i; } return null; } let arr = [0,1,2,3,4,5] console.log(find(arr, 2)) console.log(find(arr, 8))
12.获取随机数的函数方法
var rand = (function() { var today = new Date(); var seed = today.getTime(); function rnd() { seed = (seed * 9301 + 49297) % 233280; return seed / (233280.0); }; return function rand(number) { return Math.ceil(rnd(seed) * number); }; })(); console.log(rand(10))
13.获取浏览器地址栏的参数值
function GetQueryString(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)return unescape(r[2]); return null; } // 调用方法 alert(GetQueryString("参数名1")); alert(GetQueryString("参数名2")); alert(GetQueryString("参数名3"));
14.关于cookie的使用
(1)设置cookie的公用函数 function setCookie(name , value ,iDay){ var oDay = new Date(); oDay.setDate(oDay.getDate()+iDay) document.cookie = name"="value+";exprice="+oDay } (2)获取cookie的值 function getCookie(name){ var arr = document.cookie.split("; ") for(var i=0;i<arr.length;i++){ var arr2 = arr.split("=") if(arr2[0] == name){ return arr2[1] } } return "" } (3)删除cookie function removeCookie(name){ setCookie(name;1;-1) }
15.常用的 js如何判断当前运行环境
webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/), android = ua.match(/(Android);?[\s\/]+([\d.]+)?/), osx = !!ua.match(/\(Macintosh\; Intel /), ipad = ua.match(/(iPad).*OS\s([\d_]+)/), ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/), iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/), webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/), win = /Win\d{2}|Windows/.test(platform), wp = ua.match(/Windows Phone ([\d.]+)/), touchpad = webos && ua.match(/TouchPad/), kindle = ua.match(/Kindle\/([\d.]+)/), silk = ua.match(/Silk\/([\d._]+)/), blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/), bb10 = ua.match(/(BB10).*Version\/([\d.]+)/), rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/), playbook = ua.match(/PlayBook/), chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), firefox = ua.match(/Firefox\/([\d.]+)/), firefoxos = ua.match(/\((?:Mobile|Tablet); rv:([\d.]+)\).*Firefox\/[\d.]+/), ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/), webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/), safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/) 校验是否是移动端 if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){ ... }
16. 判断网页是否加载完成
document.onreadystatechange = function () { if (document.readyState == "complete") { //这里可以写页面加载完成后调用的方法 } }
17.校验图片加载失败处理函数
function preloadImages(arr) { var dfd = new $.Deferred() var newimages = [] var i = 0 var loaded = 0 var loaderr = 0 // 加载失败的图片个数 arr = ($.isArray(arr)) ? arr : [arr] for (; i < arr.length; i++) { newimages[i] = new Image() newimages[i].src = arr[i] newimages[i].onload = function() { loaded++ if (loaded === arr.length) { dfd.resolve() } } newimages[i].onerror = function() { loaded++ loaderr++ // 全部加载失败 if (loaderr === arr.length) { dfd.reject() return } if (loaded === arr.length) { dfd.resolve() } } } return dfd } preloadImages(['1.jpg', '2.jpg']).fail(function() { $('#div').text('无图片') })