JavaScript代码片段
分类:
IT文章
•
2023-11-24 19:12:43
简介:本文收集了我常用的JavaScript代码片段,欢迎提意见!
大灰狼边敲门边说:“小兔子乖乖,把门儿开开!”
小兔子听到后,连忙去开门:“来喽!”
兔妈妈对小兔子喊道:“不许开!是大灰狼!”
大灰狼在门口感叹道:“哎,骗一个女孩容易,骗一个女人难呀!”
JavaScript动态加载
//NO.1
function loadScript(url, callback){
var script = document.createElement ("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (this.readyState == "loaded" || this.readyState == "complete"){
this.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
//NO.2
function loadScript(url, callback){
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
var script = document.createElement ("script");
script.type = "text/javascript";
script.text = xhr.responseText;
document.body.appendChild(script);
callback();
}
}
};
xhr.send(null);
}
View Code
DOM加载完执行
function domLoad(fn){
if(document.addEventListener){
document.addEventListener("DOMContentLoaded", fn, false);
}else{
if(window.ActiveXObject){
document.write("<script id='ie_onload' defer src='javascript:void(0)'></script>");
document.getElementById("ie_onload").onreadystatechange = function(){
if(this.readyState == "complete"){
this.onreadystatechange = null;
fn();
}
}
}
if(/WebKit/i.test(navigator.userAgent)){
var _timer = setInterval(function(){
if(/loaded|complete/.test(document.readyState)){
clearInterval(_timer);
fn();
}
}, 10);
}
}
}
View Code
是否标准模式(IE)
function isCompatMode(){return document.compatMode == 'CSS1Compat';}
View Code
Link规则操作
//添加第一条规则
//insertRule(sheet, 'body', 'background-color:red', 0);
function insertRule(sheet, selectorText, cssText, position) {
if (sheet.insertRule) {
sheet.insertRule(selectorText + ' { ' + cssText + ' }', position);
} else if (sheet.addRule) {
sheet.addRule(selectorText, cssText, position);
}
}
//删除第一条规则
//deleteRule(sheet, 0);
function deleteRule(sheet, position) {
if (sheet.deleteRule) {
sheet.deleteRule(position);
} else if (sheet.removeRule) {
sheet.removeRule(position);
}
}
View Code
加载样式表
function addSheet(url){
var oLink = document.createElement('link'),oHead = document.getElementsByTagName('head')[0];
oLink.rel = 'stylesheet';
oLink.type = 'text/css';
oLink.href = url;
oHead.appendChild(oLink);
}
View Code
获取CSS样式
function getStyle(o, attr){
if(o.currentStyle){
return o.currentStyle[attr];
}
else{
return getComputedStyle(o,false)[attr];
}
}
View Code
getByClass
function getElementsByClassName(classname, parent, nodename) {
var parent = parent || document, nodename = nodename || "*";
if(parent.getElementsByClassName){
return parent.getElementsByClassName(classname);
}else{
var l = parent.getElementsByTagName(nodename);
return function () {
var res = [];
for (var i = 0, j = l.length; i < j; i++) {
if (l[i].className){
var name = " " + l[i].className + " ";
if (name.indexOf(" " + classname + " ") != -1) {
res.push(l[i]);
}
}
}
return res;
} ();
}
}
View Code
hasClass
function hasClass (element, className){
return element.className.match(new RegExp('(\s|^)'+ className +'(\s|$)'));
}
View Code
addClass
function addClass(element, cName) {
if (!hasClass(element, cName)) {
element.className += ' ' + cName;
}
}
View Code
removeClass
function removeClass(element, cName) {
if (hasClass(element, cName)) {
element.className = element.className.replace(new RegExp('(\s|^)' + cName + '(\s|$)'), ' ');
}
}
View Code
JSONP调用
<script src="http://www.xxx.com?name=fnCall"></script>
<script>
function fnCall(info){
// 在前台提供一个方法fnCall的方法
// http://www.xxx.com?name=fnCall 在(后台/其他页面)自动获取fnCall的名字并且执行
}
</script>
View Code
获取服务器时间
function getNowDate(callback){
var xhr = new XMLHttpRequest();
xhr.open('get', 'null.txt', true); //null.txt不存在,我们不需要
xhr.onreadystatechange = function(){
if(xhr.readyState == 3){ //状态3响应
callback(xhr.getResponseHeader('Date')); //返回时间,那么可以利用获得的时间做倒计时程序了。
}
};
xhr.send(null);
}
View Code
Cookie操作
function Cookie(name, value, options){
if(typeof value != 'undefined'){
options = options || {};
if(value === null){
options.expires = -1; //过期
}
var expires = '';
//存在时间选项
if(options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)){
var date;
if(typeof options.expires == 'number'){
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
}else{
date = options.expires;
}
expires = '; expires='+date.toUTCString();
}
var path = options.path ? '; path='+options.path : '';
var domain = options.domain ? '; domain='+options.domain : '';
var secure = options.secure ? '; secure' : '';
//写入cookie
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
}else{//读取cookie
var cookValue = null;
if(document.cookie && document.cookie != ''){
var cookie = document.cookie.split(';');
for(var i = 0, len = cookie.length; i < len; i++){
var c = cookie[i].replace(/^s+|s+$/g, '');
if(c.substring(0, name.length + 1) == (name + '=')){
cookValue = decodeURIComponent(c.substring(name.length + 1));
break;
}
}
}
return cookValue;
}
}
//设置
Cookie("user", "Jununx");
//获取
Cookie("user");
//删除
Cookie("user", null);
View Code
base64编码解码
function b64Encode(str) {
return btoa(unescape(encodeURIComponent(str)));
}
function b64Decode(str) {
return decodeURIComponent(escape(atob(str)));
}
View Code
浏览器判断
var browser = function() {
var u = navigator.userAgent.toLowerCase();
return {
version: (u.match(/.+(?:rv|it|ra|ie|chrome|micromessenger|version)[/: ]([d.]+)/) || [])[1],
safari: /safari/.test(u) && !/chrome/.test(u),
opera: /opera/.test(u),
msie: /msie|like gecko$/.test(u) && !/opera/.test(u),
firefox: /firefox/.test(u) && !/(compatible|webkit)/.test(u),
chrome: /chrome/.test(u) && /safari/.test(u),
mobile: !!/applewebkit.*mobile.*/.test(u),
ios: !!/(i[^;]+;( u;)? cpu.+mac os x/.test(u),
android: /android|linux/.test(u), // android或uc
iPhone: /iphone/.test(u),
iPad: /ipad/.test(u),
weChat: /micromessenger/.test(u) // 微信
};
};
View Code
IE版本判断
var _IE = (function(){
var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : false ;
}());
View Code
阶乘缓存
function memfactorial(n){
if(!memfactorial.cache){
memfactorial.cache = {
"0" : 1,
"1" : 1
};
}
if(!memfactorial.cache.hasOwnProperty(n)){
memfactorial.cache[n] = n * memfactorial(n - 1);
}
return memfactorial.cache[n];
}
View Code
获取字符串长度
// NO.1
String.prototype.sLen = function(){
var b = 0, l = this.length;
if(l){
for(var i = 0; i < l; i++){
if(this.charCodeAt(i) > 255){
b += 2;
}else{
b ++;
}
}
return b;
}else{
return 0;
}
};
// NO.2
String.prototype.sLen = function(){
var b = 0, l = this.length;
if(l){
for(var i = 0; i < l; i++){
var c = this.charAt(i);
if(escape(c).length > 4){
b += 2;
}else if(c != '
'){
b ++;
}
}
return b;
}else{
return 0;
}
};
// NO.3
String.prototype.sLen = function(){
var b = 0, l = this.length;
if(l){
for(var i = 0; i < l; i++){
var c = this.charAt(i);
if(/^[u0000-u00ff]$]/.test(c)){
b ++;
}else if(c != '
'){
b += 2;
}
}
return b;
}else{
return 0;
}
};
// NO.4
String.prototype.sLen = function(){
var s = this.replace(/[^x00-xff]/g, "**");
return s.length;
};
View Code
判断数据类型
var isType = function(obj, type){
return Object.prototype.toString.call(obj) === '[object '+ type +']';
};
View Code
获取窗口位置
function sereen(){
return {
left : window.screenLeft || window.scrollX,
top : window.screenTop || window.scrollY
};
}
View Code
获取可视窗口大小
function client(){
//IE6不加dtd会进入怪癖模式,client需要通过document.body获取
return {
width : document.documentElement.clientWidth || document.body.clientWidth,
height : document.documentElement.clientHeight || document.body.clientHeight
};
}
View Code
获取scrollTop
function getScrollTop(){
if(typeof pageYOffset!= 'undefined'){
return pageYOffset;
} else {
return (document.body || document.documentElement).scrollTop;
}
}
View Code
滚动到指定区域
el.scrollIntoView()
View Code
今天星期几
"今天是星期" + "天一二三四五六".charAt(new Date().getDay())
View Code
页面是否在iframe里
if(self==top){
//not in iframe
}else{
//in iframe
}
View Code
返回最小值~最大值之间随机数
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
View Code
数组去重
// NO.1
Array.prototype.unique = function() {
for(var i=0, len = this.length; i<len; i++) {
for(var j=i+1; j<len; j++) {
if(this[i] === this[j])
this.splice(j, 1);
}
}
return this;
};
// ["a","a","b"].unique();
// NO.2
Array.prototype.unique = function (){
var that = this, temp = {}, result = [];
for(var i = 0, len = that.length; i < len; i++) {
if(!temp[typeof (that[i])+that[i]]){
result.push(that[i]);
temp[typeof(that[i])+that[i]] = '1';
}
}
return result;
}
// ["a","a","b"].unique();
View Code
数组快排
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
var pivotIndex = Math.floor(arr.length / 2);
var pivot = arr.splice(pivotIndex, 1)[0];
var left = [];
var right = [];
for (var i = 0, j = arr.length; i < j; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
}
var test = quickSort([1,9,2,8,3,7,4,6,5]);
View Code
将arguments转换成数组
var arr = Array.prototype.slice.call(arguments, 0);
View Code
数组随机排序
var arr = [1, 2, 3, 4, 5];
arr.sort(function(){
return (Math.random() - 0.5);
});
View Code
获取数组中最小/大值
var max = Math.max.apply(null, array);
var min = Math.min.apply(null, array);
View Code
数组index
function index(t, arr){
if(arr.indexOf){
return arr.indexOf(t);
}
for(var i = arr.length ; i--; ){
if(arr[i]===t){
return i*1;
}
}
return -1;
}
View Code
多维数组转一维数组
function arr2ToArr(arr){
return arr.toString().split(",");
}
View Code
选择数组中两数之和等于某值的情况
// NO.1
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], result = [], count = 10;
for(var i = 0, len = arr.length; i < len; i ++){
for(var j = i + 1; j < len; j ++){
if(arr[i] + arr[j] === count){
result.push([arr[i], arr[j]]);
}
}
}
// NO.2
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], result = [], count = 10;
for(var i = 0, len = Math.round(arr.length/2); i < len; i ++){
if(arr.indexOf(count - arr[i]) !== -1){
result.push([arr[i], count - arr[i]]);
}
}
View Code
数字金额转换成大写
function digit_uppercase(n) {
var fraction = ['角', '分'];
var digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
var unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
var head = n < 0? '欠': '';
n = Math.abs(n);
var s = '';
for (var i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (var i = 0; i < unit[0].length && n > 0; i++) {
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零$/, '')
.replace(/^$/, '零')
+ unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
}
View Code
日期格式化
Date.prototype.toString=function(format,loc){
var time={};
time.Year=this.getFullYear();
time.TYear=(""+time.Year).substr(2);
time.Month=this.getMonth()+1;
time.TMonth=time.Month<10?"0"+time.Month:time.Month;
time.Day=this.getDate();
time.TDay=time.Day<10?"0"+time.Day:time.Day;
time.Hour=this.getHours();
time.THour=time.Hour<10?"0"+time.Hour:time.Hour;
time.hour=time.Hour<13?time.Hour:time.Hour-12;
time.Thour=time.hour<10?"0"+time.hour:time.hour;
time.Minute=this.getMinutes();
time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute;
time.Second=this.getSeconds();
time.TSecond=time.Second<10?"0"+time.Second:time.Second;
time.Millisecond=this.getMilliseconds();
time.Week=this.getDay();
var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"];
var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
var oNumber=time.Millisecond/1000;
if(format!=undefined && format.replace(/s/g,"").length>0){
if(loc!=undefined && loc =="en"){
MMMArr=MMMArrEn.slice(0);
WeekArr=WeekArrEn.slice(0);
}
format=format
.replace(/yyyy/ig,time.Year)
.replace(/yyy/ig,time.Year)
.replace(/yy/ig,time.TYear)
.replace(/y/ig,time.TYear)
.replace(/MMM/g,MMMArr[time.Month-1])
.replace(/MM/g,time.TMonth)
.replace(/M/g,time.Month)
.replace(/dd/ig,time.TDay)
.replace(/d/ig,time.Day)
.replace(/HH/g,time.THour)
.replace(/H/g,time.Hour)
.replace(/hh/g,time.Thour)
.replace(/h/g,time.hour)
.replace(/mm/g,time.TMinute)
.replace(/m/g,time.Minute)
.replace(/ss/ig,time.TSecond)
.replace(/s/ig,time.Second)
.replace(/fff/ig,time.Millisecond)
.replace(/ff/ig,oNumber.toFixed(2)*100)
.replace(/f/ig,oNumber.toFixed(1)*10)
.replace(/EEE/g,WeekArr[time.Week]);
}
else{
format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second;
}
return format;
}
var d=new Date();
console.log(d.toString()); //2012-7-27 9:26:52
console.log(d.toString("")); //2012-7-27 9:26:52
console.log(d.toString("yyyy-MM-dd HH:mm:ss")); //2012-07-27 09:26:52
console.log(d.toString("yyyy年MM月dd日 HH:mm:ss")); //2012年07月27日 09:26:52
console.log(d.toString("yyyy-MM-dd HH:mm:ss fff")); //2012-07-27 09:26:52 237
console.log(d.toString("yyyy年 MMM dd EEE")); //2012年 七月 27 星期五
console.log(d.toString("yyyy MMM dd EEE","en")); //2012 Jul 27 Fri
View Code
五种继承方式
//构造函数的继承的五种方式
function Animal() {
this.species = "dong wu";
}
// NO.1 构造函数绑定
function Cat(name, color) {
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
// NO.2 prototype模式
function Cat (name, color) {
this.name = name;
this.color = color;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
// NO.3 直接继承prototype
function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
// NO.4 利用空对象做中介
function Cat(name, color) {
this.name = name;
this.color = color;
}
function F(){}
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
// NO.5 拷贝继承
function Cat(name, color) {
this.name = name;
this.color = color;
}
function extend(Child, Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
}
extend(Cat, Animal);
View Code
根据生日算年龄
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
console.log(getAge("1990,1,12"));
View Code
事件绑定
var events = (function(win){
// 事件绑定
function on(el, ev, fn){
if(el.addEventlistener){
on = function (el, ev, fn) {
el.addEventlistener(ev, fn, false);
};
} else if(el.attachEvent){
on = function(el, ev, fn){
el.attachEvent('on' + ev, function(){
fn.call(el); // IE This
});
};
} else {
on = function(el, ev, fn){
el['on' + ev] = fn;
};
}
on(el, ev, fn);
}
// 解除事件绑定
function off(el, ev, fn){
if(el.removeEventlistener){
off = function (el, ev, fn) {
el.removeEventlistener(ev, fn, false);
};
} else if(el.detachEvent){
off = function(el, ev, fn){
el.detachEvent('on' + ev, fn);
};
} else {
off = function(el, ev){
el['on' + ev] = null;
};
}
off(el, ev, fn);
}
// 获取事件对象
function getEvent(ev){
return ev || win.event;
}
// 获取事件目标
function getTarget(ev){
return ev.target || ev.srcElement;
}
// 获取键值
function getKeyCode(ev){
if (typeof ev.charCode == 'number'){
getKeyCode = function(ev){
return ev.charCode;
};
} else {
getKeyCode = function(ev){
return ev.keyCode;
};
}
getKeyCode(ev);
}
// 阻止默认行为
function preventDefault(ev){
if(ev.preventDefault){
preventDefault = function(ev){
ev.preventDefault();
};
} else {
preventDefault = function(ev){
ev.returnValue = false;
};
}
preventDefault(ev);
}
// 阻止冒泡
function stopPropagation(ev){
if(ev.stopPropagation){
stopPropagation = function(ev){
ev.stopPropagation();
};
} else {
stopPropagation = function(ev){
ev.cancelBubble = true;
};
}
stopPropagation(ev);
}
return {
on: on,
off: off,
getEvent: getEvent,
getTarget: getTarget,
getKeyCode: getKeyCode,
preventDefault: preventDefault,
stopPropagation: stopPropagation
};
}(window));
View Code
自定义事件
var EventHandlers = {
events: {},
fire: function(ev, arg){
if(this.events[ev]){
var e = this.events[ev];
for(var i = 0, len = e.length; i < len; i++){
e[i](arg);
}
}
},
on: function(ev, fn){
if(!this.events[ev]){
this.events[ev] = [];
}
this.events[ev].push(fn);
},
off: function(ev, fn){
if(this.events[ev]){
var e = this.events[ev];
for(var i = 0, len = e.length; i < len; i++){
if(e[i] == fn){
e.splice(i, 1);
break;
}
}
}
}
};
View Code
加载获取图片尺寸
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
}
View Code
Object.create
var create = Object.create || function(o){
var F = function(o){};
F.prototype = o;
return new F;
};
View Code
Object.prototype.bind
var bind = Object.prototype.bind || function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
};
View Code
设置选定文本
//选定文本
function setSelectText(text, start, num) {
if (text.setSelectionRange) {
text.setSelectionRange(start,num);
text.focus();
} else if (text.createTextRange) {
var range = text.createTextRange();
range.collapse(true);
range.moveStart('character',start);
range.moveEnd('character',num - start); //用最后的位置 - 开始的位置 = 个数
range.select();
}
}
View Code
获取选择文本
function getSelectedText(id){
var o = document.getElementById(id);
if(window.getSelection) {
if(o.selectionStart != undefined && o.selectionEnd != undefined){
return o.value.substring(o.selectionStart, o.selectionEnd);
}
}
else{
return document.selection.createRange().text;
}
}
View Code
在光标位置插入字符串
// 光标位置插入字符串
function insertHtmlAtCursor(id, text){
var o = document.getElementById(id);
if (document.selection){
o.focus();
document.selection.createRange().text = text;
o.focus();
}
else if (o.selectionStart) {
var start = o.selectionStart, end = o.selectionEnd;
o.value = o.value.substring(0, start) + text + o.value.substring(end, o.value.length);
}
}
View Code
在url中查找指定参数的值
function getQuery(){
var s = (location.search.length > 0 ? location.search.substring(1) : ''),
res = {},
items = s.length ? s.split('&') : [],
item = null, name = null, value = null,
i, len = items.length;
for (i = 0; i < len; i++){
item = items[i].split('=');
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if(name.length){
res[name] = value;
}
}
return res;
}
View Code
IE6里a:hover图片缓存
document.execCommand("BackgroundImageCache",false,true);
View Code
反转文本顺序
String.prototype.reverse = function (){
if(this.length < 2){
return this;
}
var str = this.split(''), result = '', len = this.length - 1;
while(len >= 0){
result += this[len];
len --;
}
return result;
}
'反转文本顺序'.reverse();
View Code
清除空格
String.prototype.trim = String.trim || function() {
return this.replace(/^s*(.*?)s+$/, "$1")
};
View Code
加入收藏
function addFavorite(url, title) {
try {
window.external.addFavorite(url, title);
} catch(e) {
try {
window.sidebar.addPanel(title, url, "");
} catch(e) {
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
}
}
View Code
设为首页
function setHomepage(url) {
if (document.all) {
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage(url)
} else if (window.sidebar) {
if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
} catch(e) {
alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true")
}
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage', url)
}
}
View Code
insertAfter
function insertAfter(newChild,refChild){
var parElem=refChild.parentNode;
if(parElem.lastChild==refChild){
refChild.appendChild(newChild);
}else{
parElem.insertBefore(newChild,refChild.nextSibling);
}
}
View Code
innerText操作
//获取innertext
function getInnerText(element) {
if (typeof element.textContent == 'string') {
return element.textContent;
} else {
return element.innerText;
}
}
//设置innertext
function setInnerText(element, text) {
if (typeof element.textContent == 'string') {
element.textContent = text;
} else {
element.innerText = text;
}
}
View Code
获取offsetTop
//获取offsetTop
function offsetTop(element) {
var top = element.offsetTop; //第一层的距离
var parent = element.offsetParent;
while (parent !== null) {
top += parent.offsetTop;
parent = parent.offsetParent;
}
return top;
}
View Code
构建字符串的最优方法
var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
View Code
获取字符串中出现次数最多的字符
// NO.1
String.prototype.strCount = function (){
var num = 0, val = '', result = null, temp = '', that = this;
while (that) {
temp = that;
val = that.substr(0, 1);
that = that.replace(new RegExp(val, "g"), "");
if (temp.length - that.length > num) {
num = temp.length - that.length;
result = {val:val, num: num};
}
}
return result;
};
// NO.2
String.prototype.strCount = function (){
var obj = {}, num = 0, val = '';
for(var i = 0, len = this.length; i < len; i+=1){
if(!obj[this[i]]){
obj[this[i]] = [];
}
obj[this[i]].push(this[i]);
}
for(var arr in obj){
if(num < obj[arr].length){
num = obj[arr].length;
val = obj[arr][0];
}
}
return {val:val, num: num};
};
// NO.3
function strCount(str){
var o = {}, ret = {name: '', num: 0};
for(var i = 0, len = str.length; i < len; i++){
if( o[str[i]] ) {
o[str[i]]++;
}else{
o[str[i]] = 1;
}
if(ret.num < o[str[i]]){
ret.name = str[i];
ret.num = o[str[i]];
}
}
return ret;
}
// NO.4
function strCount(str){
var ret = {name: '', num: 0};
str.split('').sort().join('').replace(/(w)1+/g, function($0, $1){
if ( ret.num < $0.length ) {
ret.num = $0.length;
ret.name = $1;
}
});
return ret;
}
View Code
对象深度clone
var cloneObj = function(obj){
var newobj, s;
if(typeof obj !== 'object'){
return;
}
newobj = obj.constructor === Object ? {} : [];
if(window.JSON){
s = JSON.stringify(obj), //系列化对象
newobj = JSON.parse(s); //反系列化(还原)
}else{
if(newobj.constructor === Array){
newobj.concat(obj);
}else{
for(var i in obj){
newobj[i] = obj[i];
}
}
}
return newobj;
};
View Code
千分位表示
// NO.1
function millesimal(v){
var num = v.length%3, prev = '', next = v.substring(num), arr = [];
if(num !== 0){
prev = v.substring(0, num);
arr.push(prev);
}
for(var i = 0, len = next.length; i < len; i += 3){
arr.push(next.substr(i,3))
}
return arr.join();
}
// NO.2
function millesimal(v){
return v.toString().replace(/(?=(?!)(d{3})+$)/g, ',');
}
// NO.3
function millesimal(v){
return v.toString().replace(/B(?=(d{3})+$)/g, ',');
}
View Code
替换全部
String.prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2)
}
View Code
HTML转义
// 转义html标签
function HtmlEncode(text) {
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
}
// 还原html标签
function HtmlDecode(text) {
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
}
View Code
随机字符串(字母&数字)
function randomStringNum(len) {
var ret = "";
for( ; ret.length < len; ret += Math.random().toString(36).substr(2));
return ret.substr(0, len);
}
View Code
随机颜色
// (0xffffff+1) 表示颜色最大值(0x000000 ~ 0xffffff+1)
// <<0 表示左移一位,将颜色16进制的颜色值转成整型
// toString(16) 表示再将整型的颜色值转成16进制
// slice(-6) 表示生成的16进制值少于6位时,首尾依次补0
var getRandomColor = function(){
return '#'+('00000'+(Math.random()*(0xffffff+1)<<0).toString(16)).slice(-6);
};
View Code
curry
function currying(fn) {
var args = [].slice.call(arguments, 1);
return function() {
var newArgs = args.concat([].slice.call(arguments));
return fn.apply(null, newArgs);
}
}
// use
var test = currying(function() {
console.log(arguments);
}, 'a');
test(1);
View Code
uncurrying
Function.prototype.uncurrying = function(){
var self = this;
return function(){
return Function.prototype.call.apply(self, arguments);
}
};
View Code
函数节流
// 函数节流
var throttle = function(fn, interval){
var self = fn,
timer,
firstTime = true;
return function(){
var args = arguments,
that = this;
if(firstTime){
self.apply(that, args);
return firstTime = false;
}
if(timer){
return false;
}
timer = setTimeout(function(){
clearTimeout(timer);
timer = null;
self.apply(that, args);
}, interval || 500);
};
};
View Code
分时调用
/**
* [timeChunk 分时调用]
* @param {[type]} arr [数据]
* @param {Function} fn [处理函数]
* @param {[type]} count [执行次数]
*/
var timeChunk = function(arr, fn, count){
var obj, t, len = arr.length;
var start = function(){
for (var i = 0, obj; i < Math.min(count || 1, arr.length); i++){
obj = arr.shift();
fn(obj);
}
};
return function(){
t = setInterval(function(){
if (arr.length === 0){
return clearInterval(t);
}
start();
}, 200);
};
};
View Code
单例模式抽象
// 单例模式抽象
var getSingle = function(fn){
var res;
return function(){
return res || (res = fn.apply(this, arguments));
}
};
View Code