Authored by 周奇琪

yoho-tools init

*.iml
.idea/
.ipr
.iws
*~
~*
*.diff
*.patch
*.bak
.DS_Store
Thumbs.db
.project
.*proj
.svn/
*.swp
*.swo
*.pyc
*.pyo
.build
node_modules
_site
sea-modules
spm_modules
.cache
dist
\ No newline at end of file
... ...
dist
_site
sea-modules
spm_modules
node_modules
.git
tests
examples
test
... ...
language: node_js
node_js:
- "0.10"
install:
- npm install spm coveralls
before_script:
- node_modules/spm/bin/spm-install
script:
- node_modules/spm/bin/spm-test
after_success:
- node_modules/spm/bin/spm-test --coveralls | node_modules/.bin/coveralls
... ...
# History
---
## 0.0.1
`new` It is the first version of yoho-tools.
... ...
# yoho-tools [![spm version](http://spm.yoho.cn/badge/yoho-tools)](http://spm.yoho.cn/package/yoho-tools)
---
工具库,常用方法集合
## Install
```
$ spm install yoho-tools --save
```
## Usage
```js
var yohoTools = require('yoho-tools');
// use yohoTools
```
... ...
# Demo
---
## Normal usage
````javascript
seajs.use('index', function(yohoTools) {
});
````
... ...
{
"name": "yoho-tools",
"version": "0.0.1",
"description": "工具库,常用方法集合",
"keywords": [],
"homepage": "",
"author": "hbomb <qiqi.zhou@yoho.cn>",
"repository": {
"type": "git",
"url": ""
},
"bugs": {
"url": ""
},
"licenses": "MIT",
"spm": {
"main": "tools.js",
"dependencies": {
},
"devDependencies": {
"expect.js": "0.3.1"
}
},
"devDependencies": {
"spm": "3"
},
"scripts": {
"test": "spm test",
"build": "spm build"
}
}
... ...
var expect = require('expect.js');
var yohoTools = require('../index');
describe('yoho-tools', function() {
it('normal usage', function() {
});
});
... ...
/**
* @fileOverview 前后端的公用工具类和方法封装
* @author:Hbomb(zhouqq@yoho.cn)
* @date:2012-07-09
*/
/**
* HTML编码
*/
exports.escapeHTML = function (ret)
{
if (!ret)
{
return;
}
ret = exports.unescapeHTML(ret);
var div = document.createElement('div');
var text = document.createTextNode(ret);
div.appendChild(text);
return div.innerHTML;
};
/**
* HTML反编码
*/
exports.unescapeHTML = function (str)
{
str=str+"";
var ret = str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
ret = ret.replace(/&quot;/g, '"');
return ret;
};
/**
* js对象克隆
*/
exports.IYOHO_clone = function (myObj)
{
if (typeof(myObj) != 'object')
return myObj;
if (!myObj)
return myObj;
var myNewObj = {};
if(myObj.length)
{
myNewObj = [];
}
for (var i in myObj)
myNewObj[i] = IYOHO_clone(myObj[i]);
return myNewObj;
};
/**
* js object2Array
*/
exports.IYOHO_Object2Array = function (obj)
{
var arr = [];
for(var i in obj)
{
arr.push(obj[i]);
}
return arr;
};
/**
* 时间格式化yyyy/mm/dd
*/
exports.timeFormat = function (dt, format)
{
var dd = dt.getDate();
var mm = dt.getMonth() + 1; // January is 0!
var yyyy = dt.getFullYear();
if (dd < 10)
{
dd = '0' + dd;
}
if (mm < 10)
{
mm = '0' + mm;
}
return yyyy + format + mm + format + dd;
};
/**
* 获取url参数
*/
exports.request = function (strName)
{
var strHref = window.document.location.href;
return _request(strHref, strName);
};
/**
* 获取url参数
*/
function _request(href, strName)
{
var strHref = href;
var intPos = strHref.indexOf("?");
var strRight = strHref.substr(intPos + 1);
var arrTmp = strRight.split("&");
for (var i = 0; i < arrTmp.length; i++)
{
var arrTemp = arrTmp[i].split("=");
if (arrTemp[0].toUpperCase() == strName.toUpperCase())
return arrTemp[1];
}
return "";
}
/**
* cookie set and get
*/
exports.cookie = function (name, value, options)
{
if (typeof value != 'undefined')
{
options = options || {};
if (value === null)
{
value = '';
//options = $.extend({}, options);
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' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
}
else
{
var cookieValue = null;
if (document.cookie && document.cookie !== '')
{
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
{
var cookie = exports.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '='))
{
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
exports.trim = function( text )
{
if(String.prototype.trim)
{
return text == null?
"":
String.prototype.trim.call( text );
}
else
{
var trimLeft = /^\s+/;
var trimRight = /\s+$/;
return text == null?
"":
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
}
};
/**
* 检查email邮箱
*/
exports.IYOHO_isEmail = function (str)
{
var reg = /^\s*([A-Za-z0-9_-]+(\.\w+)*@(\w+\.)+\w{2,3})\s*$/;
return reg.test(str);
};
/**
* 检查qq号
*/
exports.IYOHO_isQQ = function (str)
{
var reg = /^[1-9]\d{4,10}$/;
return reg.test(str);
};
/**
* 检查电话
*/
exports.IYOHO_isTel = function (str)
{
var reg = /^\s*[.0-9]{8,11}\s*$/;
return reg.test(str);
};
/**
* 检查邮编
*/
exports.IYOHO_isPostcode = function(str)
{
var reg = /^[0-9]\d{5}(?!\d)/;
return reg.test(str);
};
/**
* 检测姓名非法字符
*/
exports.IYOHO_isUserName = function (str)
{
var reg = /^[^@\/\'\\\"#$%&\^\*]+$/;
return reg.test(str);
};
/**
* 检测是否合法url
*/
exports.IYOHO_isURL = function (str)
{
var reg = /^((http(s)?|ftp|telnet|news|rtsp|mms):\/\/)?(((\w(\-*\w)*\.)+[a-zA-Z]{2,4})|(((1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).){3}(1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).?))(:\d{0,5})?(\/+.*)*$/;
return reg.test(str);
};
/**
* 根据日期获取星座
*/
/**
* 摩羯座(12/22 - 1/19)、水瓶座(1/20 - 2/18)、双鱼座(2/19 - 3/20)、牡羊座(3/21 - 4/20)、金牛座(4/21 -
* 5/20)、 双子座(5/21 - 6/21)、巨蟹座(6/22 - 7/22)、狮子座(7/23 - 8/22)、处女座(8/23 -
* 9/22)、天秤座(9/23 - 10/22)、 天蝎座(10/23 - 11/21)、射手座(11/22 - 12/21)
*/
exports.getZodiac = function (month, day)
{
var d = new Date(1999, month - 1, day, 0, 0, 0);
var arr = [];
arr.push(["摩羯座", new Date(1999, 0, 1, 0, 0, 0)]);
arr.push(["水瓶座", new Date(1999, 0, 20, 0, 0, 0)]);
arr.push(["双鱼座", new Date(1999, 1, 19, 0, 0, 0)]);
arr.push(["牧羊座", new Date(1999, 2, 21, 0, 0, 0)]);
arr.push(["金牛座", new Date(1999, 3, 21, 0, 0, 0)]);
arr.push(["双子座", new Date(1999, 4, 21, 0, 0, 0)]);
arr.push(["巨蟹座", new Date(1999, 5, 22, 0, 0, 0)]);
arr.push(["狮子座", new Date(1999, 6, 23, 0, 0, 0)]);
arr.push(["处女座", new Date(1999, 7, 23, 0, 0, 0)]);
arr.push(["天秤座", new Date(1999, 8, 23, 0, 0, 0)]);
arr.push(["天蝎座", new Date(1999, 9, 23, 0, 0, 0)]);
arr.push(["射手座", new Date(1999, 10, 22, 0, 0, 0)]);
arr.push(["摩羯座", new Date(1999, 11, 22, 0, 0, 0)]);
for (var i = arr.length - 1; i >= 0; i--)
{
if (d >= arr[i][1])
return arr[i][0];
}
};
/**
* 根据年份获取生肖
*/
exports.getShengxiao= function (yyyy)
{
var arr = ['猴', '鸡', '狗', '猪', '鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊'];
return /^\d{4}$/.test(yyyy) ? arr[yyyy % 12] : null;
};
/**
* 数组去重复
*/
exports.unique = function (data)
{
data = data || [];
var a = {};
for (var i = 0, len = data.length; i < len; i++)
{
var v = data[i];
if ('undefined' == typeof(a[v]))
{
a[v] = 1;
}
}
data.length = 0;
for (var i in a)
{
data[data.length] = i;
}
return data;
};
/**
* 生成一个不重复的别名
*/
exports.genDefID = function(str)
{
var time = new Date().getTime() + "";
var id = str + "_" + (time).substring(time.length - 6) + "_" +
(Math.round(Math.random() * 1000));
return id;
};
/**
* 获取纯字符长度
*/
exports.fucCheckLength = function (strTemp)
{
var i, sum;
sum = 0;
for (i = 0; i < strTemp.length; i++)
{
if ((strTemp.charCodeAt(i) >= 0) && (strTemp.charCodeAt(i) <= 255))
sum = sum + 1;
else
sum = sum + 2;
}
return sum;
};
/**
* 截字封装(字符串,长度)
*/
exports.limitWords = function (str, len, havedot)
{
var ret = "";
var str_ = exports.unescapeHTML(str);
if (exports.fucCheckLength(str_) > len)
{
str = exports.unescapeHTML(str);
ret = subStringByByte(str, 0, len - 1);
ret = exports.escapeHTML(ret);
havedot || (ret += "...");
}
else
{
ret = str;
}
return ret;
};
/**
* 截字
* @param {} str 需要截字的字符串
* @param {} idx1 开始位置
* @param {} idx2 结束位置
* @return {}
*/
function subStringByByte (str, idx1, idx2)
{
var n = 0, start = str.length, end = str.length;
for (var i = 0; i < str.length; i++)
{
if (n <= idx1)
{
start = i;
}
if (str.charCodeAt(i) < 128)
{
n++;
}
else
{
n += 2;
}
if (n > idx2)
{
end = i;
break;
}
}
return str.substring(start, end);
};
/**
* 检测Capslock按键
*/
exports.checkCapsLock = function (e)
{
valueCapsLock = e.which;
if (valueCapsLock >= 65 && valueCapsLock <= 90 && !e.shiftKey)
{
return true;
}
else
{
return false;
}
};
/**
* 获得DOM窗口相对于window的位置
*/
exports.getPos = function (obj)
{
var curLeft = 0, curTop = 0;
if (obj.offsetParent)
{
while(obj.offsetParent)
{
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
obj = obj.offsetParent;
}
};
return [curTop, curLeft];
};
/**
* 获得相关的属性的方法
*/
exports.getCssVal = function (o, key)
{
return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
};
/**
* 判断是否数组
*/
exports.isArray = function(params)
{
return Object.prototype.toString.apply(params) === '[object Array]';
};
/**
* 日期的格式化
*/
Date.prototype.format = function(format) //author: meizz
{
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
};
if(/(y+)/.test(format))
{
format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o)
{
if(new RegExp("("+ k +")").test(format))
{
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
}
}
return format;
};
//获取flash对象
exports.getFlash = function (movieName)
{
if (navigator.appName.indexOf("Microsoft") != -1&&navigator.appVersion.indexOf("MSIE 9.0")==-1)
{
return window[movieName];
}
else
{
return document[movieName];
}
};
//判断是否有history
exports.hasHistory = function()
{
if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0))
{
if(history.length>0)
{
return true;
}
else
{
return false;
}
}
else
{
if(history.length>1)
{
return true;
}
else
{
return false;
}
}
};
// 判断对象是否是空对象
exports.isNullObj = function(obj)
{
for(var i in obj)
{
if(obj.hasOwnProperty(i))
{
return false;
}
}
return true;
};
/**
* 获取鼠标在页面上的位置
* @param ev 触发的事件
* @return x:鼠标在页面上的横向位置, y:鼠标在页面上的纵向位置
*/
exports.getMousePoint = function (ev)
{
// 定义鼠标在视窗中的位置
var point = {
x:0,
y:0
};
// 如果浏览器支持 pageYOffset, 通过 pageXOffset 和 pageYOffset 获取页面和视窗之间的距离
if(typeof window.pageYOffset != 'undefined') {
point.x = window.pageXOffset;
point.y = window.pageYOffset;
}
// 如果浏览器支持 compatMode, 并且指定了 DOCTYPE, 通过 documentElement 获取滚动距离作为页面和视窗间的距离
// IE 中, 当页面指定 DOCTYPE, compatMode 的值是 CSS1Compat, 否则 compatMode 的值是 BackCompat
else if(typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
point.x = document.documentElement.scrollLeft;
point.y = document.documentElement.scrollTop;
}
// 如果浏览器支持 document.body, 可以通过 document.body 来获取滚动高度
else if(typeof document.body != 'undefined') {
point.x = document.body.scrollLeft;
point.y = document.body.scrollTop;
}
// 加上鼠标在视窗中的位置
point.x += ev.clientX;
point.y += ev.clientY;
// 返回鼠标在视窗中的位置
return point;
}
\ No newline at end of file
... ...