Tool function - Zhang-haohua/blog GitHub Wiki
- 循环查找方式:
function formatNumber(value) {
value = value.toString();
if ( value.indexOf('.') > -1 ) {
return formatNumber(value.split('.')[0]) + '.' + value.split('.')[1];
} else {
if (value.length <= 3) {
return value;
} else {
return formatNumber(value.substr(0, value.length - 3)) + ',' + value.substr(value.length - 3);
}
}
}
- 正则方式:
"15000000".split("").reverse().join("").replace(/(\d{3})/g, "$1,").split("").reverse().join("");
"115000000".split("").reverse().join("").replace(/(\d{3})(?=[^$])/g, "$1,").split("").reverse().join("");
var str = '123123211312.333123'.replace(/(?=(?!^)(?:\d{3})+(?:\.|$))(\d{3}(\.\d+$)?)/g,',$1');
- toLocaleString函数:
15000000..toLocaleString() //15,000,000"
15000000.12.toLocaleString() //"15,000,000.12"
function formatTime(time){
// 正确时区const nowTime = moment(new Date()).utc().utcOffset(8).format('YYYY-MM-DD HH:mm:ss');
const nowTime = moment(new Date());
const Time = moment(time);
const startOfWeek = moment().startOf('week'); // 本周一0点
const startOfYesterday = moment().startOf('day').subtract(1, 'days');// 昨日0点
const endOfYesterday = moment().endOf('day').subtract(1, 'days');// 昨日23:59点前
const TimeYear = Time.get('year');// 参数的年份
const nowTimeYear = moment().year(moment().year()).startOf('year').get('year');// 本年
let displayTime = '';
if (TimeYear === nowTimeYear) { // 同年
if(moment(Time - startOfWeek).valueOf() < 0){// 本周前
displayTime = moment(Time).format('MM-DD HH:mm');
}
else if(moment(Time - startOfYesterday).valueOf() < 0 && moment(Time - startOfWeek).valueOf() >= 0){// 本周内昨日之前
displayTime = moment(Time).format('dddd HH:mm');
}
else if(moment(Time - startOfYesterday).valueOf() >= 0 && moment(Time - endOfYesterday).valueOf() < 0 && moment(Time - startOfWeek).valueOf() >= 0){// 昨日内
displayTime = Time.format('昨天 HH:mm');
}
else if(moment(Time - endOfYesterday).valueOf() >= 0 && moment(Time - startOfWeek).valueOf() >= 0){// 今天内
const timedistance = moment(nowTime - Time).utc();
const hour = timedistance.get('hour');
const minute = timedistance.get('minute');
if(hour >= 1){// 一小时前
displayTime = moment(Time).format('今天 HH:mm');
}
else if(hour < 1 && minute >= 1){// N分钟前
displayTime = moment(Time).format(`${minute} 分钟前`);
}
else {
displayTime = moment(Time).format('刚刚');
}
}
}
else {
displayTime = moment(Time).format('YYYY-MM-DD HH:mm')
}
return displayTime;
};
function isEmpty(obj){
return JSON.stringify(obj) === '{}' || JSON.stringify(obj) === '[]' || obj === undefined || obj === 'undefined' || obj === '' || obj === '-' || obj === null
};
function calculateHeight (ele) {
$('body').append('<div id="Test" style="padding:0;border:0;height:auto;width:auto;position:absolute;display:none;"></div>');
var longString = ele.text();
var eleWidth = ele.innerWidth();
var eleHeight = $('#Test').html(longString).css({'width':eleWidth,'font-size': '12px','line-height': '17px'}).height();
$('body').remove('#Test');
return eleHeight;
}
### 进阶版:
function calculateHeight(ele) {
var lines = ele.data('line');//超过几行隐藏
$('body').append('<div id="Test" style="padding:0;border:0;height:auto;width:auto;position:absolute;display:none;"></div><div id="line-clamp" style="overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: ' + lines + ';-webkit-box-orient: vertical;"></div>');
var longString = ele.text();
var eleWidth = ele.innerWidth();
var fontSize = ele.css('font-size');
var lineHeight = ele.css('line-height');
var eleHeight = $('#Test').html(longString).css({
'width': eleWidth,
'font-size': fontSize,
'line-height': lineHeight
}).height();
var eleLineClampHeight = $('#line-clamp').html(longString).css({
'width': eleWidth,
'font-size': fontSize,
'line-height': lineHeight
}).height();
$('#Test').remove();
$('#line-clamp').remove();
return eleHeight <= eleLineClampHeight && lines;//判断是否需要处理显示省略号提示框
}
可参考:
1. https://juejin.im/post/5dc15b35f265da4d432a3d10;
2. http://www.jq22.com/jquery-info8977
3. https://www.w3h5.com/post/54.html
4. https://github.com/happylindz/blog/issues/12
function clamp(ele,lineClamp){//lineClamp是行数,超过lineClamp就省略号处理
ele.each(function(){
var content = $(this).attr('data-title');//data-title需要原始文本
$(this).html(content);//初始化最开始文本
$(this).css('height','');//清空js渲染的高度
var lineHeight = parseInt($(this).css('line-height'));//行高,即每行的高度
if($(this).height() > lineClamp*lineHeight){//排除不需要省略号的情况
for(i=0; i < content.length; i++) {
$(this).html(content.substr(0, i));//从0开始添加字符串
if($(this).height() > lineClamp*lineHeight){
$(this).css({'height':lineClamp*lineHeight + 'px','overflow':'hidden'});
$(this).html(content.substr(0, i-3) + '...');
break;
}
}
}
});
}
select() 方法触发 select 事件,或规定当发生 select 事件时运行的函数。
function copyUrl(_this) {//参数必须为jq选择器
let Url2 = _this.find('.copybox');
Url2.select();
try {
document.execCommand("Copy");
alert("分享链接已复制到剪贴板!");
} catch (e) {
alert("请按ctrl+v手工复制链接");
}
}
var loadImg = function loadImg() {
var wrapper = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'body';
$(wrapper).find('.icon-load-check').each(function (index, img) {
var $img = $(img);
var className = $img.data('rel');
var hasImg = $img.data('hasimg');
var hasClass = $img.data('hasclass');
if (wrapper === 'body') {//判断是否是异步加载的图片
if (!hasImg || hasImg && (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)) {
if (hasClass) {
$img.hide();
$img.siblings('.' + className).show();
} else {
$img.siblings('.' + className).hide();
$img.show().attr("src", '../public/web/assets/[email protected]');
}
}
} else {
if (!hasImg) {
$img.hide();
$img.siblings('.' + className).show();
}
if (!hasClass) {
$img.siblings('.' + className).hide();
$img.show().attr("src", '../public/web/assets/[email protected]');
}
$img.on('error', function () {
if (hasClass) {
$img.hide();
$img.siblings('.' + className).show();
} else {
$(this).attr("src", '../public/web/assets/[email protected]');
}
});
}
});
};