Skip to content

Instantly share code, notes, and snippets.

@Leptune
Last active January 25, 2019 06:45
Show Gist options
  • Save Leptune/4681434aff31c6db63b3012684b4a9d9 to your computer and use it in GitHub Desktop.
Save Leptune/4681434aff31c6db63b3012684b4a9d9 to your computer and use it in GitHub Desktop.
前端js通用函数
// 将网络图片转换为base64url
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';//它开启了本地的跨域允许。当然服务器存储那边也要开放相应的权限才行,如果是设置了防盗链的图片在服务端就没有相应的权限的话你本地端开启了权限也是没有用的
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');//没权限的跨域图片在使用canvas.toDataURL()数据导出时会报错
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
// 获取随机数
function get_rand(min, max) {
return Math.floor(Math.random() * max) + min;
}
// 判断该变量是否是空
function isEmpty(value) {
if (!value) {
return true;
}
if ('array' == typeOf(value) || 'string' == typeOf(value)) {
return !value.length;
}
if('object' == typeOf(value)){
for(var key in value) {
if(Object.prototype.hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
return false;
}
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
// 打乱数组
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
// 前端tips弹窗,自动消失
function _shake($panel, max, per){
$panel.show();
var box_left = 0;
$panel.css({'left': box_left,'position':'relative'});
for(var i=1; i<=max; i++){
$panel.animate({left:box_left-(max-i)*per},max*per);
$panel.animate({left:box_left+2*(max-i)*per},max*per);
}
}
function tips(m) {
if (!$('#my-msg-wrap').length) {
$('body').append(`
<div id="my-msg-wrap" style="position: fixed; width: 100%; top: 0; z-index: 9999; text-align: center;">
<div id="my-msg" style="width: 50%;min-width: 100px;background-color: #03A9F4;color: #fff;border-radius: 2px;margin: 0px auto;display:none;">
<div style="padding: 12px 25px;line-height: 24px;font-weight: bold;font-size: 16px;" id="my-msg-text"></div>
</div>
</div>`);
}
$('#my-msg-text').empty().append(m);
_shake($('#my-msg'), 5, 5);
$('#my-msg').delay(1500).fadeOut('slow', function() {
$('#my-msg-wrap').remove();
});
}
// 返回变量类型
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment