我是靠谱客的博主 妩媚蜻蜓,最近开发中收集的这篇文章主要介绍项目所需的公用js方法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  以上为真实项目方法,如有需要可享受复制

颜色

// hex颜色转rgb颜色
HexToRgb(str) {
str = str.replace('#', '')
var hxs = str.match(/../g)
for (var i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16)
return hxs
},
// rgb颜色转hex颜色
RgbToHex(a, b, c) {
var hexs = [a.toString(16), b.toString(16), c.toString(16)]
for (var i = 0; i < 3; i++) {
if (hexs[i].length == 1) hexs[i] = '0' + hexs[i]
}
return '#' + hexs.join('')
},
// 加深
darken(color, level) {
var rgbc = this.HexToRgb(color)
for (var i = 0; i < 3; i++) rgbc[i] = Math.floor(rgbc[i] * (1 - level))
return this.RgbToHex(rgbc[0], rgbc[1], rgbc[2])
},
// 变淡
lighten(color, level) {
var rgbc = this.HexToRgb(color)
for (var i = 0; i < 3; i++) rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i])
return this.RgbToHex(rgbc[0], rgbc[1], rgbc[2])
}

节流

/**
*
节流(throttle):节流和防抖有点类似,节流是在规定的时间里,只执行一次,节流可以减少不断执行频率,和游戏的技能冷却时间类似。
*
使用场景:频繁触发事件,onscroll滚动,mousemove 等等
*/
// 节流
let timer, flag
function throttle(func, wait = 300, immediate = true) {
if (immediate) {
if (!flag) {
flag = true
// 如果是立即执行,则在wait毫秒内开始时执行
typeof func === 'function' && func()
timer = setTimeout(() => {
flag = false
}, wait)
}
} else {
if (!flag) {
flag = true
// 如果是非立即执行,则在wait毫秒内的结束处执行
timer = setTimeout(() => {
flag = false
typeof func === 'function' && func()
}, wait)
}
}
}

 本地缓存

const tool = {}
/* localStorage */
tool.data = {
set(table, settings) {
var _set = JSON.stringify(settings)
return localStorage.setItem(table, _set)
},
get(table) {
var data = localStorage.getItem(table)
try {
data = JSON.parse(data)
} catch (err) {
return null
}
return data
},
remove(table) {
return localStorage.removeItem(table)
},
clear() {
return localStorage.clear()
}
}
/* sessionStorage*/
tool.session = {
set(table, settings) {
var _set = JSON.stringify(settings)
return sessionStorage.setItem(table, _set)
},
get(table) {
var data = sessionStorage.getItem(table)
try {
data = JSON.parse(data)
} catch (err) {
return null
}
return data
},
remove(table) {
return sessionStorage.removeItem(table)
},
clear() {
return sessionStorage.clear()
}
}
export default tool

 封装全局 toast 提示

<!--
* @Descripttion:
* @version: css3+原生js实现toast提示层弹框(淡入淡出动画效果)
* @Author: xxx
* @Date: xxx
* @LastEditors: xxx
* @LastEditTime: xxx
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
@keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@-moz-keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@-o-keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@-ms-keyframes fadeIn {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
@-webkit-keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
@-moz-keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
@-o-keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
@-ms-keyframes fadeOut {
0% {
opacity: 1
}
100% {
opacity: 0
}
}
#toast {
background: rgba(0, 0, 0, 0.7);
color: #fff;
font-size: 14px;
line-height: 1;
padding: 10px;
border-radius: 3px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
z-index: 9999;
}
.hide {
display: none;
}
.fadeOut {
animation: fadeOut .5s;
}
.fadeIn {
animation: fadeIn .5s;
}
</style>
</head>
<body>
<script>
var toast = function (params) {
var el = document.createElement("div");
el.setAttribute("id", "toast");
el.innerHTML = params.message;
document.body.appendChild(el);
el.classList.add("fadeIn");
setTimeout(function () {
el.classList.remove("fadeIn");
el.classList.add("fadeOut");
el.addEventListener("animationend", function () {
el.classList.add("hide");
});
}, params.time);
};
//使用
toast({
message: "提交成功",
time: 1500
});
</script>
</body>
</html>

 数字格式、千位分隔、首字母大写

/**
* Number formatting
* like 10000 => 10k
* @param {number} num
* @param {number} digits
*/
export function numberFormatter(num, digits) {
const si = [
{ value: 1E18, symbol: 'E' },
{ value: 1E15, symbol: 'P' },
{ value: 1E12, symbol: 'T' },
{ value: 1E9, symbol: 'G' },
{ value: 1E6, symbol: 'M' },
{ value: 1E3, symbol: 'k' }
]
for (let i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(/.0+$|(.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
}
}
return num.toString()
}
/**
* 10000 => "10,000"
* @param {number} num
*/
export function toThousandFilter(num) {
return (+num || 0).toString().replace(/^-?d+/g, m => m.replace(/(?=(?!b)(d{3})+$)/g, ','))
}
/**
* Upper case first char
* @param {String} string
*/
export function uppercaseFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}

时间

 


getDateDiff(dateTimeStamp) {
dateTimeStamp = this.getDateTimeStamp(dateTimeStamp);
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;
var result;
var now = new Date().getTime();
var diffValue = now - dateTimeStamp;
if (diffValue < 0) {
//若日期不符则弹出窗口告之
//alert("结束日期不能小于开始日期!");
}
var monthC = diffValue / month;
var weekC = diffValue / (7 * day);
var dayC = diffValue / day;
var hourC = diffValue / hour;
var minC = diffValue / minute;
if (monthC >= 1) {
result = parseInt(monthC) + '个月前';
} else if (weekC >= 1) {
result = parseInt(weekC) + '周前';
} else if (dayC >= 1) {
result = parseInt(dayC) + '天前';
} else if (hourC >= 1) {
result = parseInt(hourC) + '个小时前';
} else if (minC >= 1) {
result = parseInt(minC) + '分钟前';
} else result = '刚刚发表';
return result;
},
//js函数代码:字符串转换为时间戳
getDateTimeStamp(dateStr) {
return Date.parse(dateStr.replace(/-/gi, '/'));
}

最后

以上就是妩媚蜻蜓为你收集整理的项目所需的公用js方法的全部内容,希望文章能够帮你解决项目所需的公用js方法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部