js 个人笔记
/*
* Created by lsw 2018-06
*/
; (function (window) {
//js ready
var ie = !!(window.attachEvent && !window.opera), wk = /webkit\/(\d+)/i.test(navigator.userAgent) && (RegExp.$1 < 525);
var fn = [], run = function () { for (var i = 0; i < fn.length; i++)fn[i](); }, d = document; d.ready = function (f) {
if (!ie && !wk && d.addEventListener) { return d.addEventListener('DOMContentLoaded', f, false); } if (fn.push(f) > 1) return;
if (ie) (function () { try { d.documentElement.doScroll('left'); run(); } catch (err) { setTimeout(arguments.callee, 0); } })();
else if (wk) var t = setInterval(function () { if (/^(loaded|complete)$/.test(d.readyState)) clearInterval(t), run(); }, 0);
};
//防止网页被嵌入框架的代码
try {
window.top.location.hostname;
if (top.location.hostname != window.location.hostname) {
top.location.href = window.location.href;
}
}
catch (e) {
top.location.href = window.location.href;
}
//内部变量
var variableObj = {
msgTips: $(document.querySelector("#msgTips")),
msgTipsBody: document.querySelector("#msgTipsBody"),
url: window.location.href,
keys: "AAnFauu4V6Zdwczo",
progressBar: document.querySelector("#progressBar")
},
initialize = {
create: function () {
return function () {
this.initialize.apply(this, arguments);
}
},
//reader初始化事件,或预操作
reader: function () {
let consoleConfig = {
o2Market: "欢迎访问:http://www.yishion.com.cn/ \n公众号:YISHION-GROUP 每周推送漂亮时尚好看的衣服!",
gongzonghao: window.location.origin +"/Content/YiSee/IMG/qrcode.jpg"
};
console.log("%c" + consoleConfig.o2Market + "\n%c ", "color: #6190e8;", "background: url(" + consoleConfig.gongzonghao + ") no-repeat left center;font-size: 300px;", ""); }
};
initialize.reader(); let NoQuery = initialize.create();
NoQuery.prototype = {
initialize: function () {
return this;
},
/*system.js 缓存全局对象 对外公布*/
elementSys: {
key: variableObj.keys
},
/*数字判断*/
digits: function (value) {
return /^\d+$/.test(value);
},
/*中文判断*/
isChinese: function (str) {
return /[\u4E00-\u9FA5]/g.test(str);
},
/*ajax 全局入口 支持登入是否超时、添加Token */
ajax: function (obj) {
var objs = $.extend({
dataType: "json",
data: obj.data,
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.error(XMLHttpRequest + "-----" + textStatus + "---" + errorThrown);
"".msgTips("请求数据失败,问题频繁出现请联系管理员。请重新刷新浏览器或者安F5刷新 <br>或者点击任意空白处继续");
console.trace();
},
success: obj.success,
timeout: 6000, //超时时间设置,单位毫秒
type: "get",
beforeSend: function (request) {
request.setRequestHeader("Authorization", variableObj.keys);
},
//当请求完成之后调用这个函数
complete: function (xmlHttpRequest, status) {
if (status === 'timeout') {
"".msgTips("请求数据时间超时6秒,问题频繁出现请联系管理员。请重新刷新浏览器或者安F5刷新 <br>或者点击任意空白处继续");
console.error("请求时间超时6秒 问题频繁出现请联系管理员");
console.trace();
}
}
}, obj);
$.ajax(objs);
},
/*ajax回调函数成功和失败判断 true 失败 false 正常*/
IsSuccessOk: function (json) {
try {
if (typeof (json) == "undefined") return true;
if (json.Result == "-1") return true;
if (json.total == 0 && json.rows != null) return true;
if (json.statusCode == "300") {
console.error("ajax success CallBack "+json.message);
return true;
}
return false;
} catch (e) {
return true;
}
},
//另类的表单数据"序列化"
GetFormParamsInfo: function ($docker) {
var jsonModle = {};
$docker.each(function () {
var fieldName = $(this).attr("name");
var fieldValue = $(this).val();
jsonModle[fieldName] = fieldValue;
});
return jsonModle;
},
//对象转化成数组
objConversionArr: function (obj) {
const arr = [];
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
arr.push(obj[i]); //属性
}
}
return arr;
},
/*canvas图片懒加载 <img class="outLogin lazyload" id="zongheNow_1" src="" data-src="/Content/YiSee/IMG/expenditure.png" />
*img class 设置lazyload , parent默认 #bodyApp
*/
renderCvs: function (parent ="#bodyApp", maxValue) {
var imgList = $('.lazyload', parent);
if (imgList.length < 1) {
return;
}
var max = maxValue || imgList.length;
for (let i = 0; i < max; i++) {
var imgId = imgList[i].id;
var imageCache = localStorage.getItem(imgId);
if (imageCache) {
imgList[i].src = imageCache;
continue;
}
var img = new Image();
img.index = i;
img.id = imgId;
img.crossorigin = "anonymous";
img.onload = function () {
var _this = this;
var zCvs = $('#' + this.id);
var domCvs = zCvs[0];
domCvs.src = this.src;
zCvs.removeClass('lazyload');
try {
var cvs = document.createElement('canvas');
cvs.style.display = 'none';
document.body.appendChild(cvs);
var rcvs = cvs.getContext('2d');
cvs.width = 140;
cvs.height = 108;
rcvs.drawImage(this, 0, 0, 140, 108);
//toDataURL()转成base64字符串
setTimeout(function () {
var data = cvs.toDataURL();
localStorage.setItem(_this.id, data);
document.body.removeChild(cvs);
}, 200);
} catch (ex) {
console.error("renderCvs" + ex);
}
}
img.src = imgList[i].getAttribute('data-src');
}
}
}; /* 时间格式化(火狐特殊处理) new Date(xx).format("yyyy-MM-dd hh:mm:ss") */
Date.prototype.format = function (format) {
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;
}
//火狐时间异常
String.prototype.replaceDate = function() {
return this.replace(/-/g, "/");
};
/* 数字*100 舍入误差 rank保留的小数位 https://segmentfault.com/q/1010000005697295 Math.signFigures(0.56 * 100)*/
Math.signFigures = function (num, rank = 6) {
if (!num) return (0);
const sign = num / Math.abs(num);
const number = num * sign;
const temp = rank - 1 - Math.floor(Math.log10(number));
let ans;
if (temp > 0) {
ans = parseFloat(number.toFixed(temp));
}
else if (temp < 0) {
ans = Math.round(number / Math.pow(10, temp)) * temp;
}
else {
ans = Math.round(number);
}
return (ans * sign);
}; /*数组插入指定位置 */
Array.prototype.insertExtend = function (index, value) {
this.splice(index, 0, value);
};
//数组是否存在指定的key 存在的key,并返回数组、和索引
Array.prototype.existsKey = function (key) {
var re = null;
for (var i = 0; i < this.length; i++) {
if (this[i][key] != null && typeof (this[i][key]) !="undefined") {
re = {
arr: this[i],
arrIndex: i
}
break;
}
}
return re;
};
//判断是否存在指定的key 存在的key 和keyValue,并返回数组、和索引
Array.prototype.existsNameyiShion = function (key, keyValue) {
var re = null;
for (var i = 0; i < this.length; i++) {
if (this[i][key] === keyValue) {
re = {
arr: this[i],
arrIndex: i
}
break;
}
}
return re;
};
//移除数组中的某元素
Array.prototype.removeExtend = function (obj) {
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
this.splice(i, 1);
break;
}
}
return this;
} //折线图 <canvas id="cv10" width="115" height="30" data-style="#000000" data-data="38,45,78,76,92,7,27,66"></canvas>
String.prototype.drawingLineCanvas = function (data, targetProperty) {
const cv = document.getElementById(targetProperty.id);
cv.width = targetProperty.width;
cv.height = targetProperty.height;
const maxNum = Math.max.apply(null, data); //求数组中的最大值
var padding = 7, //边距
arrowWidth = 7, //箭头的宽度
xLength = cv.width - 2 * padding - arrowWidth, //x轴的长度
yLength = cv.height - 2 * padding - arrowWidth, //y轴的长度
pointsWidth = xLength / (data.length + 1); //折线上每个点之间的距离
const ctx = cv.getContext("2d");//ctx.beginPath();//当前的点设置为 (0,0)
for (let i = 0; i < data.length; i++) {
const pointX = padding + (i + 1) * pointsWidth; //边距+点平均距离*(i+1)
const pointY = padding + arrowWidth + (1 - data[i] / maxNum) * yLength; //边距+(1- 值/最大值)*y坐长度(y坐长自定义长度)
ctx.lineTo(pointX, pointY);//下一个点
}
ctx.strokeStyle = targetProperty.color;//css
ctx.lineWidth = targetProperty.lineWidth;//线粗细 数字类型
ctx.stroke(); //画线
}
/* 4舍5入 保留fixed小数点 整数去掉.0 */
String.prototype.custFloats = function (value, fixed, ispercent = false) {
if (value == null || value === "undefined") return "";
var result = null;
if (typeof (value) == "string") {
if (value.indexOf(".") ===-1) {
result = value;
} else {
result= parseFloat(value).toFixed(fixed);
}
} else {
if (value.toString().indexOf(".") === -1) {
result = value;
} else {
result = parseFloat(value.toFixed(fixed));
}
}
if (ispercent && parseFloat(value)>0) {
result = result + "%";
}
return result;
}
/*数字每隔三位加逗号分开*/
String.prototype.Locale = function (value) {
if (typeof value === 'undefined' || value == null) return 0;
const temp = Number(value);
return temp<999 ? value : Number(value).toLocaleString();
};
/*设置head标题 */
String.prototype.setHeadTitle = function (element,value) {
document.querySelector(element).innerText = value;
};
/*获取url参数值 */
String.prototype.getUrlParam = function (name) {
const regExp = new RegExp('([?]|&)' + name + '=([^&]*)(&|$)');
const result = variableObj.url.match(regExp);
if (result) {
const str = decodeURIComponent(result[2]);
var arr = str.split('#');
return arr.length === 2 ? arr[0] : str;
} else {
let msg = `url:${variableObj.url}地址,无参数 ${name} 。<br>请仔细检查4秒自动关闭窗口`;
"".msgTips(msg,true);
console.error(msg);
return null;
}
};
/*信息提示 支持自定义 按esc退出 */
String.prototype.msgTips = function (info, isClose = false) {
variableObj.msgTipsBody.innerHTML = info;
variableObj.msgTips.modal();
if (isClose) {
setTimeout(function() {
variableObj.msgTips.modal('hide');
},3000);
}
};
/*load */
String.prototype.loadTips = function (isshow = false) {
var txt = ";display:none;";
if (isshow) {
txt = ";display:block;";
}
variableObj.progressBar.style = txt;
}; /*错误监听 */
window.onerror = function (msg, url, l) {
const txt = `本页中存在错误<br>
错误:${msg}<br>
地址:${url}<br>
行:${l}<br>
点击任意空白处继续或刷新浏览器,问题频繁出现请联系管理员。`; "".msgTips(txt);
console.error(txt);
return true;
}
/* 外部直 window.$sys访问或者 $sys*/
window.$sys = new NoQuery();
})(window);
js 个人笔记的更多相关文章
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- Vue.js学习笔记(2)vue-router
vue中vue-router的使用:
- js读书笔记
js读书笔记 基本类型的基本函数总结 1. Boolean() 数据类型 转换为true的值 转换为false的值 Boolean true false String 任何非空字符串 "&q ...
- React.js入门笔记
# React.js入门笔记 核心提示 这是本人学习react.js的第一篇入门笔记,估计也会是该系列涵盖内容最多的笔记,主要内容来自英文官方文档的快速上手部分和阮一峰博客教程.当然,还有我自己尝试的 ...
- JS 学习笔记--9---变量-作用域-内存相关
JS 中变量和其它语言中变量最大的区别就是,JS 是松散型语言,决定了它只是在某一个特定时间保存某一特定的值的一个名字而已.由于在定义变量的时候不需要显示规定必须保存某种类型的值,故变量的值以及保存的 ...
- node.js系列笔记之node.js初识《一》
node.js系列笔记之node.js初识<一> 一:环境说明 1.1 Linux系统CentOS 5.8 1.2 nodejs v0.10.15 1.3 nodejs源码下载地址 htt ...
- JS面向对象笔记二
菜单导航,<JS面向对象笔记一>, 参考书籍:阮一峰之<JavaScript标准参考教程> 一.构造函数和new命令 二.this关键字 三.构造函数和new命令 四.构造函 ...
- WebGL three.js学习笔记 使用粒子系统模拟时空隧道(虫洞)
WebGL three.js学习笔记 使用粒子系统模拟时空隧道 本例的运行结果如图: 时空隧道demo演示 Demo地址:https://nsytsqdtn.github.io/demo/sprite ...
- WebGL three.js学习笔记 法向量网格材质MeshNormalMaterial的介绍和创建360度全景天空盒的方法
WebGL学习----Three.js学习笔记(5) 点击查看demo演示 Demo地址:https://nsytsqdtn.github.io/demo/360/360 简单网格材质 MeshNor ...
- WebGL three.js学习笔记 创建three.js代码的基本框架
WebGL学习----Three.js学习笔记(1) webgl介绍 WebGL是一种3D绘图协议,它把JavaScript和OpenGL ES 2.0结合在一起,通过增加OpenGL ES 2.0的 ...
随机推荐
- 501. Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred ...
- Python-异常处理-66
异常和错误 # 1/0 # name # 2+'3' # [][3] #{}['k'] try: ') # 1/0 ') # name # 2+'3' # [][3] # {}['k'] ret = ...
- P2801 教主的魔法(分块入门)
两个月之前听yyr学长讲的分块,感觉是个很神奇的暴力,但到现在还是懵的一匹 #include<bits/stdc++.h> using namespace std; ; int belon ...
- pragma警告处理
使用pragma消除警告 (绝不可强行消除,因为有可能是个运行时错误) #pragma clang diagnostic push #pragma clang diagnostic ignored & ...
- git使用kdiff3合并乱码问题
https://blog.csdn.net/u011008029/article/details/72644515 在合并代码过程中发现kdiff打开的文件都是乱码,解决方案如下: 第一步:点击Set ...
- 小白月赛13 小A与小B (双向BFS)
链接:https://ac.nowcoder.com/acm/contest/549/G来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言52428 ...
- jQuery实现搜索框插件+豆瓣音乐接口实现豆瓣搜索框
jQuery实现搜索框插件 豆瓣音乐接口实现豆瓣搜索框 豆瓣接口有时不稳定,网络请求会报400,不要惊慌.我主要是练习一下jQuery的JSONP和封装插件. <div class=" ...
- CMake快速入门
参考: https://www.hahack.com/codes/cmake/ 1. 单目标文件 main.c #include <stdio.h> #include <stdlib ...
- element ui change 传递带自定义参数
@change="((val)=>{changeStatus(val, index)})" https://www.cnblogs.com/mmzuo-798/p/10438 ...
- 五十九、linux 编程—— I/O 多路复用 fcntl
59.1 介绍 前面介绍的函数如,recv.send.read 和 write 等函数都是阻塞性函数,若资源没有准备好,则调用该函数的进程将进入阻塞状态.我们可以使用 I/O 多路复用来解决此问题(即 ...