Skip to content

Instantly share code, notes, and snippets.

@inhere
Last active January 11, 2018 03:47
Show Gist options
  • Save inhere/8596e1c0e644d593cf648a7e5313f728 to your computer and use it in GitHub Desktop.
Save inhere/8596e1c0e644d593cf648a7e5313f728 to your computer and use it in GitHub Desktop.
常用的js函数,工具类封装 收集
const extra = {}
// 密码检测密码强度
extra.checkStrength = function (sValue) {
let modes = 0
if (sValue.length < 1) return modes
// 正则表达式验证符合要求的
if (/\d/.test(sValue)) modes++; //数字
if (sValue.length > 7) modes++; //长度大于7
if (/[a-z]/.test(sValue)) modes++; //小写
if (/[A-Z]/.test(sValue)) modes++; //大写
if (/\W/.test(sValue)) modes++; //特殊字符
return modes
}
// 图片预览 file 对象, 预览的img id
extra.previewImage = function (file, img) {
let preImg = $('#' + img);
if (file["files"] && file["files"][0]) {
let reader = new FileReader();
reader.onload = function (evt) {
preImg.attr({
src: evt.target.result
});
}
reader.readAsDataURL(file.files[0]);
}
}
extra.scaleImage = function (imgElem, FitWidth, FitHeight) {
let image = new Image();
image.src = imgElem.src;
if (image.width > 0 && image.height > 0) {
if (image.width / image.height >= FitWidth / FitHeight) {
if (image.width > FitWidth) {
imgElem.width = FitWidth;
imgElem.height = (image.height * FitWidth) / image.width;
} else {
imgElem.width = image.width;
imgElem.height = image.height;
}
} else {
if (image.height > FitHeight) {
imgElem.height = FitHeight;
imgElem.width = (image.width * FitHeight) / image.height;
} else {
imgElem.width = image.width;
imgElem.height = image.height;
}
}
}
}
// ajax 上传文件
extra.ajaxUpload = function (url, input, opts) {
let elem = typeof input === 'string' ? $(input) : input
// no file to upload
if (!elem[0].files[0]) {
return
}
opts = this.extend({
data: {},
onSuccess: null,
onError: null
}, opts)
let formData = new FormData()
formData.append("file", elem[0].files[0])
// 追加数据
for (let key in opts.data) {
formData.append(key, opts.data[key])
}
$.ajax({
url: url,
type: 'POST',
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
beforeSend: function () {
console.log("正在进行,请稍候... ...")
},
success: opts.onSuccess,
error: opts.onError
})
}
/**
* 回到顶部
* @param {string} wrapper
* @param {string} icon
*/
extra.backTop = function (wrapper, icon) {
let slideToTop = $("<div></div>")
slideToTop.html(icon ? icon : '<i class="fa fa-chevron-up"></i>')
slideToTop.css({
position: 'fixed',
bottom: '20px',
right: '25px',
width: '40px',
height: '40px',
color: '#eee',
'font-size': '',
'line-height': '40px',
'text-align': 'center',
'background-color': '#222d32',
cursor: 'pointer',
'border-radius': '5px',
'z-index': '99999',
opacity: '.7',
'display': 'none'
})
slideToTop.on('mouseenter', function () {
$(this).css('opacity', '1')
})
slideToTop.on('mouseout', function () {
$(this).css('opacity', '.7')
})
$(wrapper).append(slideToTop)
$(window).scroll(function () {
if ($(window).scrollTop() >= 150) {
if (!$(slideToTop).is(':visible')) {
$(slideToTop).fadeIn(500);
}
} else {
$(slideToTop).fadeOut(500);
}
})
$(slideToTop).click(function () {
$("body").animate({
scrollTop: 0
}, 500);
})
}
/************************************************
* helper functions
************************************************
*/
function noop() {
}
function is_undefined(obj) {
return typeof obj === 'undefined'
}
function is_null(obj) {
return obj === null
}
function is_function(item) {
if (typeof item === 'function') {
return true
}
let type = Object.prototype.toString(item)
return type === '[object Function]' || type === '[object GeneratorFunction]'
}
function is_string(obj) {
return typeof obj === 'string'
}
function is_array(obj) {
return Array.isArray(obj) || obj instanceof Array
}
function is_object(obj) {
return toString.call(obj) === '[object Object]'
}
function is_empty_object(obj) {
if (typeof obj !== 'object') {
return true;
}
return Object.keys(obj).length === 0;
}
// 检测是不是扁平对象 (使用 “{}” 或 “new Object” 创建).
function is_plain_object(obj) {
if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) {
return false
}
return !(obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf'))
}
function in_array (arr, item) {
return arr.indexOf(item) > -1
}
function is_numeric(value) {
let type = typeof value;
return (type === 'number' || type === 'string') && !Number.isNaN(value - Number.parseFloat(value));
}
function json_encode(obj) {
return JSON.stringify(obj)
}
function json_decode(str) {
return JSON.parse(str)
}
/************************************************
* helper
************************************************
*/
const toString = Object.prototype.toString
const EmptyArray = []
const util = {
// helper method
isUndefined: is_undefined,
isNull: is_null,
isFunction: is_function,
isString: is_string,
isArray: is_array,
isObject: is_object,
isNumeric: is_numeric,
// number
toFixed(num, decimals) {
decimals = decimals || 2
return (num * 1).toFixed(decimals)
},
// string
lcFirst (str) {
return str.substr(0, 1).toLowerCase() + str.slice(1)
},
ucFirst (str) {
return str.substr(0, 1).toUpperCase() + str.slice(1)
},
trim (str){
return str.replace(/(^\s*)|(\s*$)/g, "");
},
ltrim (str) {
return str.replace(/(^\s*)/g, "");
},
rtrim () {
return this.replace(/(\s*$)/g, "");
},
// object
isEmptyObject: is_empty_object,
// array
inArray: in_array,
arrayIfy(obj, start, end) {
return EmptyArray.slice.call(obj, start, end)
},
// 合并2个对象的内容
extend(dst, src) {
if (Object.assign) {
return Object.assign({}, dst, src)
}
for (let key in src) {
if (src.hasOwnProperty(key))
dst[key] = src[key]
}
return dst
},
// 合并多个对象的内容到第一个对象。
extend2(out) {
out = out || {}
for (let i = 1; i < arguments.length; i++) {
if (!arguments[i])
continue
for (let key in arguments[i]) {
if (arguments[i].hasOwnProperty(key))
out[key] = arguments[i][key]
}
}
return out
},
// 合并第二个数组内容到第一个数组
merge(...args) {
return [].concat(...args)
},
clone(src) {
return extend({}, src)
},
// json
jsonEncode(obj) {
return json_encode(obj)
},
jsonDecode(str) {
return json_decode(str)
},
toJson (_form) {
// to json object
return JSON.parse(JSON.stringify(_form))
},
// other
bindLeaveTips () {
window.beforeunload = function () {
return '您输入的内容尚未保存,确定离开此页面吗?'
}
},
unbindLeaveTips () {
window.onbeforeunload = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment