javascript工具代码
1. JS面对对象写法
(function (window) {
function cardManager() {
return new cardManager.prototype.init();
}
cardManager.prototype = {
constructor : cardManager,
init : function () {
}
};
cardManager.prototype.init.prototype = cardManager.prototype;
window.cardManager = cardManager;
})(window);
2. 下载文件到本地函数
function download(filename, content) {
var urlObject = window.URL || window.webkitURL || window;
var downloadData = new Blob([content]);
var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
save_link.href = rlObject.createObjectURL(downloadData);
save_link.download = filename;
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(ev);
}
3. base64编码函数
function base64Code(str,isEncode=true) {
return isEncode ? btoa(encodeURIComponent(str)) : decodeURIComponent(atob(str));
}
4. 检查url函数
function check_url(_url){
var str=_url;
var Expression=/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
var objExp=new RegExp(Expression);
if(objExp.test(str)==true)return true;else return false;
}
5. 检查url函数plus
function isURL(str_url) {
var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?"
+ "(([0-9]{1,3}\.){3}[0-9]{1,3}"
+ "|"
+ "([0-9a-z_!~*'()-]+\.)*"
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\."
+ "[a-z]{2,6})"
+ "(:[0-9]{1,4})?"
+ "((/?)|"
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
var re = new RegExp(strRegex);
return re.test(str_url);
}
6. js读取本地文件
function jsReadFiles(files) {
if (files.length) {
var file = files[0];
var reader = new FileReader();
if (/text+/.test(file.type)) {
reader.onload = function() {
$('body').append('<pre>' + this.result + '</pre>');
}
reader.readAsText(file);
} else if(/image+/.test(file.type)) {
reader.onload = function() {
$('body').append('<img src="' + this.result + '"/>');
}
reader.readAsDataURL(file);
}
}
}
7. js读取文本防止乱码的实现
function readFile(file) {
var reader,$body,type,arr,suffix;
reader = new FileReader();
$body = $('body');
type = file.type;
arr = file.name.split('.');
suffix = arr[arr.length -1];
if(type.indexOf('text')!= -1 || suffix == 'md')
{
reader.readAsText(file);
reader.onload = function() {
if(this.result.indexOf('�') != -1)
{
reader = new FileReader();
reader.readAsText(file,'gb2312');
reader.onload = function(){
$body.prop('res',this.result);
};
}
else $body.prop('res',this.result);
};
}
return suffix;
}
8. jquery实时监控输入框
$('body').on('propetychange input', '输入框选择器', function () {
});
9. 生成随机RGBA颜色
function randomRgbaColor(a=1) {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return `rgba(${r},${g},${b},${a})`;
10.格式化获得当前时间
function getCurrentTime() {
var myDate,year,mon,date,h,m,s,week,weeks;
myDate = new Date();
year = myDate.getFullYear();
mon = myDate.getMonth() + 1;
date = myDate.getDate();
h = myDate.getHours();
m = myDate.getMinutes();
s = myDate.getSeconds();
week = myDate.getDay();
mon = toDouble(mon);
date = toDouble(date);
h = toDouble(h);
m= toDouble(m);
s = toDouble(s);
weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
return (`${year}-${mon}-${date} ${h}:${m}:${s} ${weeks[week]}`);
}
function toDouble(n) {
return n > 9 ? n : '0' + n;
}
11. 左右滑动动画
function slideAbout($jqObj,speed=300,success=(e)=>{}) {
$jqObj.animate({width:'show'},speed,function (e) {
success(e);
});
}
12. 滚动条到指定位置滑动效果
function scrollAnimate($container,$target,speed=300){
$container.animate({scrollTop: getPosition($target[0]).top}, speed);
function getPosition(element) {
let actualLeft = element.offsetLeft,
actualTop = element.offsetTop,
current = element.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
actualTop += current.offsetTop;
current = current.offsetParent;
}
return {
left: actualLeft,
top: actualTop
};
}
}
13. 滚动条监控
function windowEvent() {
$(window).scroll(function () {
let dst = $(document).scrollTop();
}
}
14. textarea输入Tab的处理
function addTabEvent() {
$("textarea").on('keydown',function(e){
if(e.keyCode === 9){
e.preventDefault();
let
indent = ' ',
start = this.selectionStart,
end = this.selectionEnd,
selected = window.getSelection().toString();
selected = indent + selected.replace(/\n/g,'\n'+indent);
this.value = this.value.substring(0,start) + selected + this.value.substring(end);
this.setSelectionRange(start+indent.length,start+selected.length);
return false;
}
});
}
15. 快速获得QueryString
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var url = decodeURI(decodeURI(window.location.search))
var r = url.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return '';
}
16. 计算一个字符串数组中最大宽度
function calculateMaxWidth(arr, fontSize="1rem"){
let width = 0
let html = document.createElement("span")
const maxlength = Math.max(...arr.map(s=> s ? s.length : 0))
const string = arr.find(s=>(s?.length || 0) === maxlength)
html.innerText = str
html.className = "getTextWidth"
html.style.fontSize = fontSize
document.querySelector('body').appendChild(html)
width = document.querySelector(".getTextWidth").offsetWidth
document.querySelector(".getTextWidth").remove()
return {width,string}
}
17. 读取Excel表格
function readExcel(files, rABS=false) {
function bin2str(data) {
let o = "",
l = 0,
w = 10240;
for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
return o;
}
return new Promise((resolve, reject)=>{
if(!XLSX)reject(new Error('Require Import SheetJS! More Information:http://sheetjs.com'))
const filesLength = files.length
const resultList = []
let cursor = 0
const handleLoader = e=>{
try {
const result = e.target.result
resultList.push(rABS ? XLSX.read(btoa(bin2str(result)), {type: 'base64'}) :
XLSX.read(result, {type: 'binary'}))
if(++cursor === filesLength)
resolve(resultList)
}catch (e) {reject(e)}
}
[...files].forEach(file=>{
const reader = new FileReader()
reader[rABS ? 'readAsArrayBuffer' : 'readAsBinaryString'](file)
reader.onload = handleLoader
})
})
}
18. 获取QueryString的全部参数
function GetRequest(url) {
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}