BiugleJS-只罗列部分代码(2019.12)
biugleJS — CSS
代码语言:javascript复制/**
autor: doubleam
introduction: biugle.css
**/
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
doubleam get 20191126
*/
/* 使用bootstrap的话,他默认使用了normalize.css,二者有些差别,不过你可以后引用bootstrap,也可以不引用此文件(reset.css) */
/* 推荐引入:
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="biugleJS/js/biugle.min.js"></script>
<link type="text/css" rel="stylesheet" href="biugleJS/css/biugle.min.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="fontawesome/css/fontawesome.min.css">
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* biugle */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.biu-row{
display: flex;
flex-direction: row;
}
.biu-row-re{
display: flex;
flex-direction: row-reverse;
}
.biu-col{
display: flex;
flex-direction: column;
}
.biu-col-re{
display: flex;
flex-direction: column-reverse;
}
.biu-row-center{
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.biu-col-center{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
/* others */
.biu-360{
transition-property: all;
transition-duration: 1.35s;
}
.biu-360:hover{
-webkit-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-ms-transform: rotate(360deg);
-transform: rotate(360deg);
transform: rotate(360deg);
}
.biu-666:hover{
transform: rotate(666turn);
transition-delay: 1s;
transition-property: all;
transition-duration: 59s;
transition-timing-function: cubic-bezier(.34,0,.84,1);
-moz-transition-timing-function: cubic-bezier(.34,0,.84,1);/* Firefox 4 */
-webkit-transition-timing-function: cubic-bezier(.34,0,.84,1);/* Safari 和 Chrome */
-o-transition-timing-function: cubic-bezier(.34,0,.84,1);/* Opera */
}
a:hover,button:hover,img:hover,code:hover,pre:hover,samp:hover,kbd:hover,menu:hover,nav:hover,footer:hover,ruby:hover,rp:hover,rt:hover,h1:hover,h2:hover,h3:hover,h4:hover,h5:hover{
cursor: pointer;
}
textarea {
resize: none;
}
:checked label{
font-weight: bolder;
}
input[type='number']{
text-align: right;
}
/* unimportant */
.biu-footer{
width: 100%;
display: block;
text-align: center;
position: fixed;
bottom: 0;
left: 0;
font-weight: bolder;
font-size: 1rem;
padding: 0.5%;
color: white;
background-color: rgba(0,0,0,0.15);
}
.biu-footer>span>a{
text-decoration: none;
}
.biu-footer>span>a:hover{
color: chocolate;
text-decoration: underline;
}
.biu-dialog{
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
background-color:rgba(0,0,0,0.3);
z-index: 999;
display: none;
}
#dark-theme-img{
width: 3vw;
height: 3vw;
position: fixed;
z-index: 999;
left: -1.5vw;
top: 0;
transition-duration: 0.6s;
}
#dark-theme-img:hover{
transform: rotate(360deg);
left: 0;
width: 3.5vw;
height: 3.5vw;
}
@media (max-width: 999px) {
#dark-theme-img {
display: none;
}
}
/* CHROME浏览器中自定义滚动条样式 */
/* 滚动条的宽度 */
::-webkit-scrollbar {
width:0.6vw;
height:0.6vw;
background-color:rgba(255,255,255,0.1);
}
/* ::-webkit-scrollbar-track-piece滚动条凹槽的颜色,还可以设置边框属性。 */
::-webkit-scrollbar-track {
-webkit-box-shadow:inset 0 0 0.6rem rgba(0,0,0,0.3);
background-color:#888;
}
::-webkit-scrollbar-track-piece{
background-color:#999;
}
/* 滚动小条的设置 */
::-webkit-scrollbar-thumb {
-webkit-box-shadow:inset 0 0 0.6rem rgba(0,0,0,.3);
background-color:#2f2f2f;
}
::-webkit-scrollbar-thumb:hover{
background-color:chocolate;
}
biugleJS — JS
代码语言:javascript复制/**
autor: doubleam
introduction: biugle.js
**/
/**
* ---------------BiugleJS START---------------
*/
Date.prototype.format = function (fmt = "yyyy-mm-dd hh:ii:ss") {
let o = {
'm ': this.getMonth() 1,
'd ': this.getDate(),
'h ': this.getHours(),
'i ': this.getMinutes(),
's ': this.getSeconds(),
'Q ': Math.floor((this.getMonth() 3) / 3),
'S': this.getMilliseconds()
};
if (/(y )/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() "").substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('(' k ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" o[k]).substr(("" o[k]).length)));
}
}
return fmt;
};
/**
* Biugle
*/
function Biugle() {
var _proto = Biugle.prototype;
/**
* 人性化时间
*/
_proto.timeSince = (date, longago = false, formater = "yyyy-mm-dd hh:ii:ss") => {
if (!date) {
return;
}
date.replace(/-/g, '/'); // 虽然 win 浏览器两种符号都可以,但是需兼容 ios。
let dateTS = new Date(date);
let seconds = Math.floor((new Date() - dateTS) / 1000); // 看情况是否` -8*3600`(8小时)
let interval = Math.floor(seconds / (24 * 3600));
if (longago) {
interval = Math.floor(seconds / (30 * 24 * 3600));
if (interval >= 4) {
return dateTS.format(formater);
}
if (interval >= 1) {
return interval " 月前";
}
interval = Math.floor(seconds / (7 * 24 * 3600));
if (interval >= 1) {
return interval " 周前";
}
}
if (interval >= 8) {
return dateTS.format(formater);
}
interval = Math.floor(seconds / (24 * 3600));
if (interval >= 1) {
return interval " 天前";
}
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
return interval " 小时前";
}
interval = Math.floor(seconds / 60);
if (interval >= 1) {
return interval " 分钟前";
}
return "刚刚";
};
/**
* 时间格式化
*/
_proto.timeFormat = (date, formater = null) => {
if (!date) {
return;
}
let dateTS = new Date(date.replace(/-/g, '/'));
return dateTS.format(formater || 'yyyy-mm-dd hh:ii');
};
/**
* 当前时间 使用此JS后可以使用 newDate().format() 实现
*/
_proto.nowTime = (type = 1) => {
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
hour = (hour < 10) ? ("0" hour) : hour;
minute = (minute < 10) ? ("0" minute) : minute;
second = (second < 10) ? ("0" second) : second;
if (type === 1) {
return year "-" month "-" day " " hour ":" minute ":" second;
}
if (type === 2) {
return year "/" month "/" day " " hour ":" minute ":" second;
}
if (type === 3) {
return year "年" month "月" day "日" " " hour ":" minute ":" second;
}
};
/**
* 过去某个点到现在过去的时间
*/
_proto.date2Now = (date) => {
if (!date) {
return;
}
let now = new Date();
let run = new Date(date);
let runTime = (now - run) / 1000,
days = Math.floor(runTime / 60 / 60 / 24),
hours = Math.floor(runTime / 60 / 60 - (24 * days)),
minutes = Math.floor(runTime / 60 - (24 * 60 * days) - (60 * hours)),
seconds = Math.floor((now - run) / 1000 - (24 * 60 * 60 * days) - (60 * 60 * hours) - (60 * minutes));
if (String(hours).length === 1) {
hours = "0" hours;
}
if (String(minutes).length === 1) {
minutes = "0" minutes;
}
if (String(seconds).length === 1) {
seconds = "0" seconds;
}
let runTimes = {"days": days, "hours": hours, "minutes": minutes, "seconds": seconds};
return runTimes;
};
/**
* 现在到未来某个点的剩余时间
*/
_proto.now2Date = (date) => {
if (!date) {
return;
}
let startDate = new Date();
let endDate = new Date(date);
let t = endDate.getTime() - startDate.getTime();
let d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
let hasTimes = {"days": d, "hours": h, "minutes": m, "seconds": s};
return hasTimes;
};
/**
* 将时间字符串转换为时间差距分钟
*/
_proto.getTimeSinceMinute = (date) => {
if (!date) {
return;
}
let dateTS = new Date(date.replace(/-/g, '/'));
let seconds = Math.floor((new Date() - dateTS) / 1000);
return Math.floor(seconds / 60);
};
/**
* 控制台打印信息
* @param {String} siteName 网站名称
* @param {String} siteUrl 网站地址
* @param {String} email 联系邮箱
* @param {String} info 网站简介
*/
_proto.consoleInfo = (siteName = "biugle", siteUrl = "https://www.biugle.cn", email = "biugle@yeah.net", info = "hello biugle!") => {
console.log(`%c网站名称%c${siteName}`, "line-height:28px;padding:4px;background:#a1afc9;color:#000;font-size:16px;margin-right:15px", "color:#3fa9f5;line-height:28px;font-size:16px;");
console.log(`%c网站地址%c${siteUrl}`, "line-height:28px;padding:4px;background:#a1afc9;color:#000;font-size:16px;margin-right:15px", "color:#00bc12;line-height:28px;font-size:16px;");
console.log(`%c联系邮箱%c${email}`, "line-height:28px;padding:4px;background:#a1afc9;color:#000;font-size:16px;margin-right:15px", "color:#ff9900;line-height:28px;font-size:16px;");
console.log(`%c${info}`, "line-height:28px;padding:5px;color:#fff;font-weight:bolder;font-size:16px;background-color:chocolate;color:#fff;");
if (window.console && window.console.log) {
console.log(`%c页面加载消耗了 %c${(Math.round(100 * performance.now()) / 100 / 1e3).toFixed(2)}s`, "background:#fff;color:#333;text-shadow: 0 0 2px #eee, 0 0 3px #eee, 0 0 3px #eee, 0 0 2px #eee, 0 0 3px #eee;", "color:tomato;font-weight:bolder;");
localStorage.getItem("access") || localStorage.setItem("access", (new Date).getTime());
let e = new Date(parseInt(localStorage.getItem("access")));
let o = `${e.getFullYear()}年${e.getMonth() 1}月${e.getDate()}日`;
let t = 0;
localStorage.getItem("hit") ? t = parseInt(localStorage.getItem("hit")) : localStorage.setItem("hit", 0);
localStorage.setItem("hit", t);
console.log(`%c这是你自 %c${o} %c以来第 %c${t} %c次在本站打开控制台,你想知道什么秘密吗~`, "", "color:chocolate;font-weight:bolder;", "", "color:chocolate;font-weight:bolder;", "");
}
};
/**
* 选项卡离开提示
* @param {String} leaveInfo 离开时显示内容
* @param {String} comeInfo 进入时显示内容
*/
_proto.setTitleStatus = (leaveInfo = " (╥﹏╥) 你快回来 ~ ", comeInfo = " (∩_∩) 欢迎回来 ~ ") => {
let OriginTitle = document.title;
let titleTime;
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'hidden') {
document.title = leaveInfo;
clearTimeout(titleTime);
} else {
document.title = comeInfo OriginTitle;
titleTime = setTimeout(function () {
document.title = OriginTitle;
}, 1500);
}
});
};
/**
* 添加复制内容
* @param {String} content 内容来源、版权信息等。
*/
_proto.setCopyEvent = (content = "www.biugle.cn") => {
document.addEventListener('copy', function (event) {
var clipboardData = event.clipboardData || window.clipboardData;
if (!clipboardData) {
return;
}
var text = window.getSelection().toString();
if (text) {
event.preventDefault();
clipboardData.setData('text/plain', text `nnn${content}`);
}
});
};
/**
* 格式化字符串,转实体字符,去前后空格。
* @param {String} str 待格式化字符串
* @returns {String} 格式化后的字符串
*/
_proto.strFormat = (str) => {
str = str.toString().replace(/^s |s $/g, "");
let div = document.createElement('div');
div.textContent = str;
let formatString = div.innerHTML;
return formatString;
};
/**
* 去除空格
* @param {String} str 待去空格的字符串
* @param {Number} type 1:去前后空格,2:去前空格,3:去后空格,4:去所有空格
* @returns {String} 格式化后的字符串
*/
_proto.trim = (str, type = 1) => {
switch (type) {
case 1:
case 'ba':
return str = str.toString().trim();
case 2:
case 'b':
return str = str.toString().replace(/^[s]*/, '');
case 3:
case 'a':
return str = str.toString().replace(/[s]*$/g, "");
case 4:
case 'all':
return str = str.toString().replace(/s/g, "");
default:
return str;
}
};
/**
* 大小写转换
* @param {String} str 待转换的字符串
* @param {Number} type 1:全部大写,2:全部小写,3:首字母大写,4:首页母小写
* @returns {String} 转换后的字符串
*/
_proto.charSet = (str, type = 1) => {
switch (type) {
case 1:
return str.toString().toUpperCase();
case 2:
return str.toString().toLowerCase();
case 3:
return str.toString().replace(/^(w)(w )/, function (v, v1, v2) {
return v1.toUpperCase() v2.toLowerCase();
});
case 4:
return str.toString().replace(/^(w)(w )/, function (v, v1, v2) {
return v1.toLowerCase() v2.toUpperCase();
});
default:
return str;
}
};
/**
* 将资料放到指定的 HTML 当内容,class name 自动将_转换为-
*/
_proto.dataTo = (key, value) => {
$(key.toString().replace(/_/g, '-')).html(value).val(value);
return this;
};
/**
* 取数组或者对象的第一个值
*/
_proto.firstVal = (objOarray) => {
for (let key in objOarray) {
let result = objOarray[key];
return result;
}
};
/**
* 获取一定范围的随机数
*/
_proto.getRandNum = (min = 0, max = 10) => {
return Math.floor(min Math.random() * (max - min 1));
};
/**
* 随机生成颜色
*/
_proto.getRandColor = () => {
return '#' ('00000' (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
};
/**
* 插入某元素到指定Element之前
*/
_proto.insertAfter = (newElement, targetElement) => {
let parent = targetElement.parentNode;
if (parent.lastElementChild === targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextElementSibling);
}
};
/**
* 设置cookie
*/
_proto.setCookie = (name, value, days) => {
days = days || 30; //没有设置有效期,默认有效期是30天
var exp = new Date(); //获取当前日期
exp.setTime(exp.getTime() days * 24 * 60 * 60 * 1000); //设置过期日期
document.cookie = name "=" escape(value) ";expires=" exp.toGMTString() ";path=/";
};
/**
* 获取cookie
*/
_proto.getCookie = (name) => {
var arr, reg = new RegExp("(^| )" name "=([^;]*)(;|$)");
if (arr === document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
};
/**
* 删除cookie
*/
_proto.delCookie = (name) => {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval !== null)
document.cookie = name "=" cval ";expires=" exp.toGMTString() ";path=/";
};
/**
* 获取浏览器类型和版本
*/
_proto.getExplore = () => {
let sys = {},
ua = navigator.userAgent.toLowerCase(),
s;
(s = ua.match(/rv:([d.] )) like gecko/)) ? sys.ie = s[1] :
(s = ua.match(/msie ([d.] )/)) ? sys.ie = s[1] :
(s = ua.match(/edge/([d.] )/)) ? sys.edge = s[1] :
(s = ua.match(/firefox/([d.] )/)) ? sys.firefox = s[1] :
(s = ua.match(/(?:opera|opr).([d.] )/)) ? sys.opera = s[1] :
(s = ua.match(/chrome/([d.] )/)) ? sys.chrome = s[1] :
(s = ua.match(/version/([d.] ).*safari/)) ? sys.safari = s[1] : 0;
// 根据关系进行判断
if (sys.ie) {
return ('IE: ' sys.ie);
}
if (sys.edge) {
return ('EDGE: ' sys.edge);
}
if (sys.firefox) {
return ('Firefox: ' sys.firefox);
}
if (sys.chrome) {
return ('Chrome: ' sys.chrome);
}
if (sys.opera) {
return ('Opera: ' sys.opera);
}
if (sys.safari) {
return ('Safari: ' sys.safari);
}
return 'UnkonwnExplore';
};
/**
* 获取操作系统类型
*/
_proto.getOS = () => {
let userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || '';
let vendor = 'navigator' in window && 'vendor' in navigator && navigator.vendor.toLowerCase() || '';
let appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || '';
if (/mac/i.test(appVersion)) {
return 'MacOSX';
}
if (/win/i.test(appVersion)) {
return 'Windows';
}
if (/linux/i.test(appVersion)) {
return 'Linux';
}
if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) {
return 'Ios';
}
if (/android/i.test(userAgent)) {
return 'Android';
}
if (/win/i.test(appVersion) && /phone/i.test(userAgent)) {
return 'WindowsPhone';
}
return 'UnknowOS';
};
/**
* 判断是否为邮箱地址
*/
_proto.isEmail = (str) => {
return /w ([- .]w )*@w ([-.]w )*.w ([-.]w )*/.test(str);
};
/**
* 判断是否为身份证号
*/
_proto.isIdCard = (str) => {
return /^(^[1-9]d{7}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{3}$)|(^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])((d{4})|d{3}[Xx])$)$/.test(str);
};
/**
* 判断是否为手机号
*/
_proto.isPhoneNum = (str) => {
return /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(str);
};
/**
* 判断是否为URL地址
*/
_proto.isUrl = (str) => {
return /[-a-zA-Z0-9@:%._ ~#=]{2,256}.[a-z]{2,6}b([-a-zA-Z0-9@:%_ .~#?&//=]*)/i.test(str);
};
/**
* rmb现金额转大写
*/
_proto.rmbUpper = (n) => {
let fraction = ['角', '分'];
let digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
let unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
let head = n < 0 ? '欠' : '';
n = Math.abs(n);
let s = '';
let fraLen = fraction.length;
for (let i = 0; i < fraLen; i ) {
s = (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (let i = 0; i < unit[0].length && n > 0; i ) {
var p = '';
for (let 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(/^整$/, '零元整');
};
/**
* 除法函数
*/
_proto.div = (div1, div2) => {
let div1FloatLen = 0, div2FloatLen = 0, tempDiv1 = div1.toString(), tempDiv2 = div2.toString();
try {
div1FloatLen = tempDiv1.split(".")[1].length;//获取小数长度
} catch (e) {
}
try {
div2FloatLen = tempDiv2.split(".")[1].length;
} catch (e) {
}
return (Number(tempDiv1.replace(".", "")) / Number(tempDiv2.replace(".", ""))) * Math.pow(10, div2FloatLen - div1FloatLen);//转化整数计算再使用科学计数法转化小数位
};
/**
* 乘法函数
*/
_proto.times = (mul1, mul2) => {
let mulFloatLen = 0, tempMul1 = mul1.toString(), tempMul2 = mul2.toString();
try {
mulFloatLen = tempMul1.split(".")[1].length;
} catch (e) {
}
try {
mulFloatLen = tempMul2.split(".")[1].length;
} catch (e) {
}
return Number(tempMul1.replace(".", "")) * Number(tempMul2.replace(".", "")) / Math.pow(10, mulFloatLen);
};
/**
* 加法函数
*/
_proto.add = (add1, add2) => {
let add1FloatLen = 0, add2FloatLen = 0, multiple = 1;
try {
add1FloatLen = add1.toString().split(".")[1].length;
} catch (e) {
}
try {
add2FloatLen = add2.toString().split(".")[1].length;
} catch (e) {
}
multiple = Math.pow(10, Math.max(add1FloatLen, add2FloatLen));
return (add1 * multiple add2 * multiple) / multiple;
};
/**
* 减法函数
*/
_proto.sub = (sub1, sub2) => {
let sub1FloatLen = 0, sub2FloatLen = 0, multiple = 1;
try {
sub1FloatLen = sub1.toString().split(".")[1].length;
} catch (e) {
}
try {
sub2FloatLen = sub2.toString().split(".")[1].length;
} catch (e) {
}
multiple = Math.pow(10, Math.max(sub1FloatLen, sub2FloatLen));
return parseFloat(((sub1 * multiple - sub2 * multiple) / multiple));
};
/**
* 四舍五入
*/
_proto.round = (number, d) => {
let tempNum = number "";//example-0.155
d = (!d) ? 0 : d;
if (d == 0) {//保留0位小数直接取整就好了
return Math.round(number);
}
if (tempNum.indexOf(".") === -1) {
tempNum = ".";
}
tempNum = new Array(d 1).join("0");//-0.15500
if (new RegExp("^(-|\ )?(\d (\.\d{0," (d 1) "})?)\d*$").test(tempNum)) {// 【/^(-| )?(d (.d{0,3})?)d*$/】
let tempStr = "0" RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, flag = true; //tempStr:数值部分(0.155)加0是为了防止产生进位,pm:正负号(-),a:小数点 小数(.155)长度为上一条正则表达式得出的结果(此处为{0,3}),flag:首位0是否未产生进位。
if (a == d 1 1) {//一个1为小数点,一个1为需要多一位数字才能判断,此处判断是否有足够的数字来得出结果。
a = tempStr.match(/d/g);//["0", "0", "1", "5", "5"]
let aLen = a.length;
if (parseInt(a[aLen - 1]) > 4) {//保留小数的后一位是否大于4
for (let i = aLen - 2; i >= 0; i--) {
a[i] = parseInt(a[i]) 1;
if (a[i] == 10) {
a[i] = 0;
flag = (i != 1);//判断首位0是否未产生进位,false为产生了进位,后续不裁剪首位0(因为i==1时,首位0发生了变化,0变为1)。
} else
break;
}
}
tempStr = a.join("").replace(new RegExp("(\d )(\d{" d "})\d$"), "$1.$2");//【/(d )(d{2})d$/】$1至少包含一个数字,$2必须为保留的小数位,结尾必须有一个数字,所以如果00155,d=2,结果为00.15,若d=1,则结果为001.5。
}
if (flag) {//如果首位0未产生进位,去掉多余的0。
tempStr = tempStr.substr(1);
}
return parseFloat((pm tempStr).replace(/.$/, ""));//返回浮点数,以防万一去掉结尾的小数点(.)。
}
};
/**
* 数组最大值
*/
_proto.arrMax = (arr = [], s2n = false) => {
return Math.max(...arr.map((num) => {
return (s2n) ? ((isNaN(Number(num))) ? -Infinity : Number(num)) : ((this.isNumber(num)) ? Number(num) : -Infinity);
}));
};
/**
* 数组最小值
*/
_proto.arrMin = (arr = [], s2n = false) => {
return Math.min(...arr.map((num) => {
return (s2n) ? ((isNaN(Number(num))) ? Infinity : Number(num)) : ((this.isNumber(num)) ? Number(num) : Infinity);
}));
};
/**
* 数组数字排序
*/
_proto.arrNumSort = (arr = [], desc = false, from = true, s2n = false) => {
let newArr = [];
if (s2n) {
arr.forEach((item, index) => {
(isNaN(item)) ? arr[index] = item : newArr.push(Number(item));
});
} else {
arr.forEach((item, index) => {
(isNumber(item)) ? newArr.push(item) : arr[index] = item;
});
}
let result = (from) ? Array.from([...new Set(newArr)]).sort((a, b) => {
return a - b;
}) : newArr.sort().sort((a, b) => {
return a - b;
});
return (desc) ? result.reverse() : result;
};
/**
* 数组字符串排序
*/
_proto.arrStrSort = (arr = [], desc = false, from = true) => {
let newArr = [];
arr.forEach((item, index) => {
return(isString(item)) ? newArr.push(item) : arr[index] = item;
});
let result = (from) ? Array.from([...new Set(newArr)]).sort().sort((a, b) => {
return a.length - b.length;
}) : newArr.sort().sort((a, b) => {
return a.length - b.length;
});
return (desc) ? result.reverse() : result;
};
/**
* 是否字符串
* @returns {boolean}
*/
_proto.isString = (str) => {
return (typeof (str) === 'string') && str.constructor === String;
};
/**
* 是否日期
* @returns {boolean}
*/
_proto.isDate = (date) => {
return (typeof (date) === 'object') && date.constructor === Date;
};
/**
* 是否对象 此处应该增加function判断
* @returns {boolean}
*/
_proto.isObject = (obj) => {
return (typeof (obj) === 'object') && obj.constructor === Object;
};
/**
* 是否数组 Array.isArray
* @returns {boolean}
*/
_proto.isArray = (arr) => {
return (typeof (arr) === 'object') && arr.constructor === Array;
};
/**
* 是否数值
* @returns {boolean}
*/
_proto.isNumber = (num) => {
return (typeof (num) === 'number') && num.constructor === Number && !isNaN(num);
};
/**
* 严格判断是否为整数或者小数
* @param {mixed} originValue 原始变量
* @param {boolean} strict 是否严格匹配
* @param {boolean} more 是否返回更多信息
* @returns {boolean}
* @name Biugle#isDigit
* @function
*/
_proto.isDigit = (originValue, strict = false, more = false) => {
let regPattern = new RegExp('^(\-?[1-9]\d*|0)(\.\d*[1-9])?$', 'g');
let value = strict ? originValue : parseFloat(originValue), result = regPattern.test(value), integer, decimal;
if (result) {
integer = parseInt(RegExp.$1);
decimal = parseFloat(RegExp.$2);
}
return more ? { result, value, integer, decimal, originValue } : result;
};
/**
* 是否 Function
* @param {mixed} func 传入值
* @returns {boolean}
* @name Biugle#isFunction
* @function
*/
_proto.isFunction = (func) => {
// ({}) instanceof Object; // true
// ([]) instanceof Object; // true
// ([]) instanceof Array; // true
// (new Date()) instanceof Object; // true
// (new Date()) instanceof Date; // true
return func instanceof Function;
// typeof func === 'function' && obj.constructor === Function;
// Object.prototype.toString.call(func) === '[object Function]';
// Function.prototype.isPrototypeOf(func); // true
};
/**
* 判断变量类型
* @param {mixed} val 传入变量
* @returns {string}
* @name Biugle#typeof
* @function
*/
_proto.typeof = (val) => {
let typeStr = Object.prototype.toString.call(val);
// return typeStr?.replace(/[|]/g, '')?.split(' ')?.[1]?.toLowerCase();//待浏览器支持,目前兼容性较差。
return typeStr.replace(/[|]/g, '').split(' ')[1].toLowerCase();
};
/**
* 是否为空
* @param {mixed} biugle 传入变量
* @returns {boolean}
* @name Biugle#empty
* @function
*/
_proto.empty = (biugle) => {
if (typeof biugle === "boolean") {
return false; //此处方法定义布尔型不算空
}
// if (Object.is(NaN, biugle)) {
// return true; //此处方法定义 NaN 算空,下面 !biugle 也可以判断。
// }
if (biugle === "null") {
return true; //检验字符串类型的 null
}
if (biugle === "undefined") {
return true; //检验字符串类型的 undefined
}
if (!biugle && biugle !== 0) {
return true; //检验 undefined 和 null ""
}
if (Array.isArray(biugle) && biugle.length === 0) {
return true; //检验空数组
}
if (Object.prototype.toString.call(biugle) === "[object Object]" && Object.keys(biugle).length === 0) {
return true; //检验空对象,仅判断普通对象,不考虑字符串对象、时间、等等。
}
return false;
};
/**
* 复制事件
*/
_proto.copyContent = (targetDom, addMsg = null) => {
let Msg = (!targetDom.innerText) ? targetDom.value : targetDom.innerText;
let tempDom = document.createElement('input');
let info = "复制成功!";
tempDom.style.position = "absolute";
tempDom.style.top = "-5201314px";
tempDom.style.left = "-5201314px";
tempDom.value = Msg;
tempDom.value = (addMsg === null) ? "" : addMsg;
document.body.appendChild(tempDom);
targetDom.blur();
tempDom.select();
try {
document.execCommand('copy');
} catch (err) {
info = "浏览器不支持此操作,请手动复制。";
}
document.body.removeChild(tempDom);
console.log(info);
return Msg;
};
/**
* 取得参数
*/
_proto.querystring = (key, url) => {
let pathname = url || location.pathname;
url = url || location.search;
let filename = pathname.substring(pathname.lastIndexOf('/') 1);
let paramMap = {
'./': filename || undefined
};
let querystring = (url.indexOf('?') === 0) ? url.substring(1) : url;
if (querystring.length !== 0) {
let parts = querystring.split('&');
for (let i = 0; i < parts.length; i ) {
let component = parts[i].split('=');
let paramKey = decodeURIComponent(component[0]);
let paramVal = decodeURIComponent(component[1]);
if (!paramMap[paramKey]) {
paramMap[paramKey] = paramVal;
continue;
}
!Array.isArray(paramMap[paramKey]) && (paramMap[paramKey] = Array(paramMap[paramKey]));
paramMap[paramKey].push(paramVal);
}
}
return (key) ? paramMap[key] || undefined : paramMap;
};
/**
* 格式化字节
*/
_proto.formatBytes = (bytes, precision) => {
let units = ['B', 'KB', 'MB', 'GB', 'TB'];
let pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
pow = Math.min(pow, units.length - 1);
bytes /= (1 << (10 * pow));
let unit = (units[pow]) ? units[pow] : units[0];
return bytes.toFixed(precision || 2) ' ' unit;
};
/**
* 将字符串转成 base64
*/
_proto.base64Encode = (str) => {
return btoa(str).replace(/ //g, '-_').replace(/=/g, '');
};
/**
* 将base64 字符串译码
*/
_proto.base64Decode = (str) => {
let remainder = str.length % 4;
let padlen;
if (remainder) {
padlen = 4 - remainder;
str = str.repeat('=', padlen);
}
return atob(str.replace('-_', ' /'));
};
}
var $b = new Biugle();
Number.prototype.add = function (num) {
return $b.add(this, num);
};
Number.prototype.sub = function (num) {
return $b.sub(this, num);
};
Number.prototype.times = function (num) {
return $b.times(this, num);
};
Number.prototype.div = function (num) {
return $b.div(this, num);
};
Number.prototype.round = function (d) {
return $b.round(this, d);
};
/**
* ---------------BiugleJS END---------------
*/