轻设计 / 轻生活 / 轻日记 / 轻梦想
=== zhoumojianshe ===
前 言
youtiy-js-utils 收集了一些项目实战通用方法代码,记录于此,以便后用,同时也分享给大家,后期会持续更新,由于手持端设备兼容有所差别,建议在PC端查阅
正 文
1、JS仿jQuery根据class获取元素
getClass(tagName, className) //获得标签名为tagName,类名className的元素 { if (document.getElementsByClassName) //支持这个函数 { return document.getElementsByClassName(className); } else { var tags = document.getElementsByTagName(tagName); //获取标签 var tagArr = []; //用于返回类名为className的元素 for (var i = 0; i < tags.length; i++) { if (tags[i].class == className) { tagArr[tagArr.length] = tags[i]; //保存满足条件的元素 } } return tagArr; } }
调用方法:
let tt=this.getClass("div","sidebar-container")[0];
2、JS获取cookie
getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(";"); for (var i = 0; i < ca.length; i++) { var c = ca[i]; console.log(c); while (c.charAt(0) == " ") c = c.substring(1); if (c.indexOf(name) != -1) { return c.substring(name.length, c.length); } } return ""; }
3、JS截取字符串
cutString(str, len) { //length属性读出来的汉字长度为1 if (str.length * 2 <= len) { return str; } var strlen = 0; var s = ""; for (var i = 0; i < str.length; i++) { s = s + str.charAt(i); if (str.charCodeAt(i) > 128) { strlen = strlen + 2; if (strlen >= len) { return s.substring(0, s.length - 1) + "..."; } } else { strlen = strlen + 1; if (strlen >= len) { return s.substring(0, s.length - 2) + "..."; } } } return s; }
4、JS日期格式化
export function dateFtt(time,fmt) { //author: meizz let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { time = parseInt(time) } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } var o = { "M+" : date.getMonth()+1, //月份 "d+" : date.getDate(), //日 "h+" : date.getHours(), //小时 "m+" : date.getMinutes(), //分 "s+" : date.getSeconds(), //秒 "q+" : Math.floor((date.getMonth()+3)/3), //季度 "S" : date.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var 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; }
调用方法:
dateFtt(new Date(), "yyyy-MM-dd hh:mm:ss") dateFtt(时间戳, "yyyy-MM-dd")
5、获取url参数
function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; }
调用方法:
var Request = GetRequest(); var deptCode = Request['deptCode'];