小项目-前端-总结
该项目前端展示部分主要以表单列表为主:
1、整理一份base.css公共样式 每个项目都可以用上(主要包括初始化样式,
布局样式,做界面内容前都先把最外层布局写好
.layout-auto,.layout { margin-left: auto;margin-right: auto;}
.layout-auto { width: 100%;min-width: 1000px; }
.layout {width: 1000px; } 中间内容的宽度
,公共弹出层,项目几个主色.c-col-red .c-col-blue等,常用的字体间距.fs14 .fs16 .fs18 .ml10 .mr10 .mt10 .mb10等,超出部分省略 等)
2、编写公共的form表单样式,包括input label text button textarea radio checkbox 等个别的错误提示error
不同颜色的按钮及hover和disable时的样式
3、列表以table去做布局,<colgroup>标签,对表格的列th tr进行组合,列的样式只要写1次再<col/>上即可应用到所有列上
<table> <colgroup> <col style="width: 200px;" /> <col style="width: 200px;" /> <col/> </colgroup> <thead> <tr> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <td>小白</td> <td>男</td> <td>25</td> </tr> <tr> <td>花花</td> <td>男</td> <td>25</td> </tr> </tbody> </table>
4、列表以验证用jq的vaildate.js校验
5、
(1)自定义错误提示
<script> function showError($obj,msg){ $obj.parents("input-box").find(".error-tip").show().html(msg); }
showError($("#txtName"),"请输入用户名");
</script>
<form class="formBox"> <div class=input-info> <label for="txtName">用户名:</label> <div class="input-box"> <input type="text" placeholder="请输入用户名" id="txtName" name="Name"/> <div class="error-tip"></div> </div> </div> </form>
(2)表单的正则表达式
// 是否邮箱 function isEmail(email) { return /^([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\\.][a-z]{2,5}([\\.][a-z]{2})?$/.test(email); } // 是否手机 function isMobile(mobile) { return /^(0|86|17951)?(13[0-9]|17[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/.test(mobile); } // 是否账号 function isAccount(account) { return /^[0-9a-zA-Z\s]+$/.test(account); }
// 匹配日期格式 yyyy-mm-dd hh:mm
var regExp = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d$/;
$(function(){ emailVerfiy(); }) function emailVerfiy(){ var email1 = "111@qq.com"; var email2 = "111qq.com"; console.log(isEmail(email1));//true console.log(!isEmail(email2));//true console.log(isEmail(email2));//false //true才执行提示错误 if(!isEmail(email2)) { console.log("邮箱格式不正确"); } }
html中直接正则限制输入:
onkeyup="this.value = this.value.replace(/\D/g, '');" 只能输入数字,将非数字字符用""取代 onkeyup="this.value = this.value.replace(^[^\u4e00-\u9fa5]{0,}$, '');" 不能输入中文 this.value = this.value.replace(/[^\w\.\/]/ig, '');只能输入数字和字母 onkeyup="this.value = toHalf(this.value);" 输入全角转化为半角 onkeyup="this.value = this.value.replace(/^\s+|\s+$/g,'');" 去掉文本框头尾空格
onkeyup="value=value.replace(/[^\d^\.]+/g,'')" 只能输入数字和小数点 // 全角转换为半角 function toHalf(str) { var tmp = ""; for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375) { tmp += String.fromCharCode(str.charCodeAt(i) - 65248); } else if (str.charCodeAt(i) == 12288) { tmp += String.fromCharCode(32); } else { tmp += String.fromCharCode(str.charCodeAt(i)); } } return tmp; }
6、form表单中的input[type='reset']自带有初始化其他表单元素的值的功能
7、提交表单时的验证,多个验证方法的情况
$("btnSubmit").click(function(){ var verifyVal = emailVerify(); verifyVal = verifyVal && imgCodeVerify(); })
8、ajax发送请求-封装方法
// 发送请求 (回调方) function sendReq(url, param, callback, failCallback) { $.ajax({ type: "post", url: url + "?" + (new Date().getTime()),//+后面为了清除缓存 data: param, contentType: "application/x-www-form-urlencoded", dataType: "json", success: function (result) { callback && callback(result); /*if(callback){ callback(result); }*/ }, error: function (e) { failCallback && failCallback(); } }); } //使用:(实现方) function updatePayPwd(){ sendReq("/User/UpdatePayPwd", { pwd: pwd, payPwd: payPwd }, function (result) { if(result.Success){ //执行成功操作 }else{ //执行失败操作 } } }
回调函数的好处:
(1)可以让实现方,根据回调方的多种形态进行不同的处理和操作。(ASIHttpRequest)
(2)可以让实现方,根据自己的需要定制回调方的不同形态。(UITableView)
(3)可以将耗时的操作隐藏在回调方,不影响实现方其它信息的展示。
(4)让代码的逻辑更加集中,更加易读。
9、手机端界面
#smVerify input,#accountVerify input"为界面的文本框,手机上点击文本框时,底部fixed或absolute的内容会被跑到键盘上面。
// 解决手机键盘弹出底部logo跑到键盘上的问题
<script> var viewHeight = window.innerHeight; $("#smVerify input").focus(function () { $(".page").css("height", viewHeight); }).blur(function () { $(".page").css("height", "100%"); }); $("#accountVerify input").focus(function () { $(".page").css("height", viewHeight); }).blur(function () { $(".page").css("height", "100%"); }); </script>
10、手机端粘贴触发事件可用
$("#accountVerify input").on('input', function () {
aVerify();
});
iphone上 文本框上边框出现阴影:
解决:
input{-webikit-apperaance:none;}
11、浏览器屏幕发生改变触发的事件
$(window).resize(function(){
//方法内容
});
12、获取验证码 倒计时
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>倒计时</title> </head> <body> <input type="button" value="获取验证码" id="getCode"/> <script src="Static/Js/jquery.js"></script> <script> // 验证码发送倒计时 function codeCountDown(obj, wait) { if (wait <= 0) { $(obj).removeClass("disable").prop("disabled", false).val("获取验证码"); } else { if (!$(obj).hasClass("disable")) { $(obj).addClass("disable").prop("disabled", "disabled"); } $(obj).val("重新获取(" + wait + ")"); wait--; setTimeout(function () { codeCountDown(obj, wait); }, 1000); } } $(function(){ $("#getCode").click(function(){ codeCountDown($(this), 10); }) }); </script> </body> </html>
13、一个元素绑定多个事件
<script> //一个元素绑定多个事件 $("#tab .more").hover(function(){ $("#moreList").removeClass("hide"); },function(){ //离开事件 $("#moreList").addClass("hide"); }).click(function(){ console.log("click事件"); }); </script>
14、placeholder样式 兼容多种浏览器
::-webkit-input-placeholder {color: #bbb;}
/* Mozilla Firefox 4 to 18 */
:-moz-placeholder { color: #bbb; opacity: 1;}
/* Mozilla Firefox 19+ */
::-moz-placeholder {color: #bbb;opacity: 1; }
:-ms-input-placeholder {color: #bbb; }
15、window.onload = function(){}和 $(window).load(function(){})和$(document).ready(function(){})
(1) js中的window.onload等价于jq的$(window).load(funciton(){}) // 必须等到界面所有内容加载完成再执行
(2)$(document).ready(function(){})简写为$(function(){}) // DOM结构绘制完成就执行 不必等到全部加载完
16、$(document).on("click","指定元素",function(){})和 $("指定元素").click(function(){})区别
前者将事件绑定在document上,动态产生的新元素只要符合指定元素 也会被绑定事件,.click绑定的 动态生成的元素 则没有事件
17、系统遮罩层和提示层
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>遮罩层</title> <style> /* 提示层 */ .sys-tip {display: none; position: fixed;z-index: 100000000;min-width: 150px;height: 30px;line-height: 30px;padding: 0 10px;border-radius: 2px;vertical-align: middle;font-size: 12px;text-align: center;font-weight: 600;top: 30px;left: 50%;} .sys-tip.tip-success{color:#3c763d;background-color:#cbf0c6;border:1px solid #bae9b4} .sys-tip.tip-error{color:#a94442;background-color:#f2dede;border:1px solid #ebccd1} .sys-tip.tip-warn{color:#8a6d3b;background-color:#fcf8e3;border:1px solid #faebcc} /* 弹出层 */ .sys-pop-wrap{position: fixed;left: 0;top: 0; width: 100%;height: 100%;display: none;z-index: 1000000;} .sys-pop-wrap .sys-pop-mask{background:#000;width:100%;height:100%;filter:Alpha(opacity=50);-moz-opacity:0.5;opacity:0.5; } .sys-pop-wrap .sys-pop-mask iframe,.sys-pop-wrap .sys-pop-main .pop-cont iframe{ width: 100%;height: 100%;border: 0 none; } .sys-pop-wrap .sys-pop-mask iframe { filter:Alpha(opacity=0);-moz-opacity:0;opacity:0; } .sys-pop-wrap .sys-pop-main{ position: absolute;left: 50%;top: 50%;margin-left: -400px; width: 800px;background: #fff;z-index: 1000001;} .sys-pop-wrap .sys-pop-main .pop-tit{ height:42px;padding:0 20px;font-size:16px;color:#222;line-height:42px;background: #F6F5FA;} .sys-pop-wrap .sys-pop-main .pop-tit .close{ width:16px;height:16px;margin-top:13px;background: url(/Static/Images/Common/close.png);cursor: pointer; } .sys-pop-wrap .sys-pop-main .pop-cont { overflow: hidden; } .sys-pop-wrap .sys-pop-main .pop-cont .pop-loading { text-align: center;width: 100%;height: 100%; } .sys-pop-tip-wrap .sys-pop-main { width: 350px;height: 220px;margin-left: -175px;margin-top: -110px; } .sys-pop-tip-wrap .sys-pop-main .pop-cont{ padding:40px 20px 20px; height: 44px; line-height: 22px; text-align: center;border: 0;font-size: 14px; } .sys-pop-tip-wrap .sys-pop-main .pop-ft { margin-bottom: 30px;text-align: center; } .sys-pop-tip-wrap .sys-pop-main .pop-ft .btn { background-color: #2d2d2d;padding: 0 9px;line-height: 24px;display: inline-block; border-radius: 2px;color: #fff; } .sys-pop-loading-wrap .sys-pop-main{ background: none; } .sys-pop-loading-wrap .sys-pop-main .pop-cont { border: none;color: #fff; } </style> </head> <body> <button id="btnClick">点击我出现遮罩</button> <script src="Static/Js/jquery.js"></script> <script> $(function(){ $("#btnClick").click(function(){ $.systemTip("error", "失败啦"); var loading = $.loadingTip(); setTimeout(function(){ loading.remove(); },2000); }) }) $(function(){ // 提示,success, wran, error $.systemTip = function (tip, msg) { $("#__sys_tip").remove(); var systemTip = $("<div id='__sys_tip' class='sys-tip'></div>"); systemTip.addClass("tip-" + tip); systemTip.text(msg); systemTip.show().appendTo("body"); systemTip.css({ "margin-left": -(systemTip.width() / 2) + "px" }); setTimeout(function () { systemTip.remove(); }, 4000); }; // 加载中提示 $.loadingTip = function() { var tag = $('<div class="sys-pop-wrap sys-pop-loading-wrap"><div class="sys-pop-mask" ><iframe scrolling="no"src="about:blank"></iframe></div></div>').show().appendTo('body'); var main = $('<div class="sys-pop-main"></div>').appendTo(tag); $('<div class="pop-cont"><table class="pop-loading"><tr><td>loading...</td></tr></table></div>').appendTo(main); return tag; }; }) </script> </body> </html>
18、使用validate.js进行表单验证
valid()检验是否验证通过 boolean
validate()验证所选的form
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vaildate</title> <style> .error{display: inline-block;color:red;} </style> </head> <body> <form id="passForm"> <label>姓名:</label><input placeholder="请输入姓名" name="txtName"/> <label>电话:</label><input placeholder="请输入电话" name="txtTel"/> <input type="button" value="提交" id="btnSubmit"> </form> <script src="Static/Js/jquery.js"></script> <script src="Static/Js/jquery.validate.js"></script> <script> $(function(){ validateForm(); $("#btnSubmit").click(function(){ console.log($("#passForm").valid());//false if(!$("#passForm").valid()){ return false; } }) }); function validateForm(){ return $("#passForm").validate({ onfocusout: function (element) { $(element).valid(); },//失去焦点时触发 onkeyup: function (element, event) { if(/^\s+/.test(this.elementValue(element))){ //去除左侧空格 var value = this.elementValue(element).replace(/^\s+/g, ""); $(element).val(value); } }, rules: { txtName: { required: true }, txtTel:{ required: true } }, messages: { txtName: { required: "请输入姓名" }, txtTel:{ required: "请输入电话" } } }); } </script> </body> </html>
若button为type="submit",则可用表单submit提交方法,这样写:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vaildate</title> <style> .error{display: inline-block;color:red;} </style> </head> <body> <form id="passForm"> <label>姓名:</label><input placeholder="请输入姓名" name="txtName"/> <label>电话:</label><input placeholder="请输入电话" name="txtTel"/> <!-- <input type="button" value="提交" id="btnSubmit">--> <input type="submit" value="提交" id="btnSubmit"/> </form> <script src="Static/Js/jquery.js"></script> <script src="Static/Js/jquery.validate.js"></script> <script> $(function(){ validateForm(); /*$("#btnSubmit").click(function(){ console.log($("#passForm").valid());//false if(!$("#passForm").valid()){ return false; } })*/ $("#passForm").submit(function(){ console.log($("#passForm").valid());//false if(!$("#passForm").valid()){// valid()验证表单 结果值的boolean return false; } }); }); function validateForm(){ return $("#passForm").validate({ //validate()调用jq的表单验证 onfocusout: function (element) { $(element).valid(); },//失去焦点时触发 onkeyup: function (element, event) { if(/^\s+/.test(this.elementValue(element))){ //去除左侧空格 var value = this.elementValue(element).replace(/^\s+/g, ""); $(element).val(value); } }, rules: { txtName: { required: true }, txtTel:{ required: true } }, messages: { txtName: { required: "请输入姓名" }, txtTel:{ required: "请输入电话" } } }); } </script> </body> </html>
19、callback && callback()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>inputBlur失去焦点</title> </head> <body> <input id="bankName" placeholder="请输入银行名称"/> <span class="error"></span> <script src="Static/Js/jquery.js"></script> <script src="Static/Js/jquery.validate.js"></script> <script> $(function(){ inputBlur("#bankName", verifyBankName);// 鼠标失去焦点之后回调verifyBankName() }); function inputBlur(obj, callback) { $(document).on("blur", obj, function () { callback && callback(); //回调函数的理解:函数a有一个参数,这个参数是函数b,当a执行完后执行函数b,这个过程叫回调 /*第一个callback相当于 if(callback){callback();} 先判断是否存在callback再执行回调callback(),防止不声明callback就运行导致报错 */ }); } function verifyBankName() { var bankName = $.trim($("#bankName").val()); if (!bankName) { $(".error").text("请输入银行名称"); return false; } else { $(".error").text("已输入"); return true; } } </script> </body> </html>
20、截取url后面的参数
界面1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="NameUpdate.html?NameId=20">点我转到NameUpdate.html修改界面</a> </body> </html>
界面2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>获取url问号后面所带参数</title> </head> <body> <script src="Static/Js/jquery.js"></script> <script> $(function(){ alert("我截取到的url的参数是:"+getUrlParam("NameId")); }); // 获取URL中的request参数 function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) { return decodeURIComponent(r[2]); } else { return ""; } } </script> </body> </html>
21、编写移动端底部的到底提示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我是有底线的~</title> <style> /* 底线 */ .bottomTip{position:relative;text-align:center;color:#000;font-size:.6rem;margin: 1rem 0;} .bottomTip:before,.bottomTip:after{content:'';position:absolute;top:.4rem;width:30%;height:1px;background: #000;} .bottomTip:before{ left: 0;} .bottomTip:after{ right: 0;} </style> </head> <body> <div class="bottomTip">我的有底线的~</div> </body> </html>
22、文本框输入的时间不能小于当前时间(比较时间戳)
function getTime(day) { var re = /(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:\s+(\d{1,2}):(\d{1,2}):(\d{1,2}))?/.exec(day); return new Date(re[1], (re[2] || 1) - 1, re[3] || 1, re[4] || 0, re[5] || 0, re[6] || 0).getTime(); } // 判断预约时间是否大于当前时间 function compareTime() { var nowDate = new Date().getTime(); var appointDate = new Date($.trim($("#txtTime").val())).getTime(); if (nowDate > appointDate) { $("#meetTimeError").text("预约时间不能小于当前时间"); return false; } else { $("#meetTimeError").text(""); return true; } }
23、给文本框输入数字时,自动从右向左 每3位添加1个逗号
function toThousands(newnum) { //每隔3位,用逗号隔开 var result = [], counter = 0; newnum = (newnum || 0).toString().split(''); for (var i = newnum.length - 1; i >= 0; i--) { counter++; result.unshift(newnum[i]); if (!(counter % 3) && i != 0) { result.unshift(','); } } return result.join(''); } // 从右向左每3位加一个逗号 function joinVal(n) { var b = parseInt(n).toString(); var len = b.length; if (len <= 3) { return b; } var r = len % 3; return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(","); }
//以上两个结合,数字和输入小数点,保留小数点后2位
//千位分隔符
function toThousands(num) {
var xiaoshu = "";
var zhengshu = "";
t = num.toString();
if (t.indexOf('.') > 0) {
var index = t.indexOf('.');
xiaoshu = t.slice(index, t.length);
zhengshu = t.slice(0, index);
} else {
zhengshu = t;
}
var zhengshu = (zhengshu || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
var result = zhengshu + xiaoshu;
return result;
}
// 使用
直接toThousands("文本框的值");
使用:
$(document).on("blur", '#txtTurnoverPerYear', function () { turnoverPerYearVerify(); }); $(document).on("keyup", "#txtTurnoverPerYear", function () { turnoverPerYearVerify(); }); function turnoverPerYearVerify() { var money = $.trim($("#txtTurnoverPerYear").val().replace(/,/g, ""));// 将文本框的逗号去掉 if (money.length != 0) { money = money.replace(/^0*/gi, "");//匹配文本框中的数字 $("#txtTurnoverPerYear").val(toThousands(money));//调用分割逗号的方法并再次重现赋值给文本框 } if (money.length == 0) { $("#txtTurnoverPerYear-error").text("请输入与正确的金额").show(); return false; } else if (money.length > 16) { $("#txtTurnoverPerYear-error").text("金额长度不能超过16位").show(); return false; } else if (money.charAt(0) == '0' || !isMoney(money)) { $("#txtTurnoverPerYear-error").text("请输入与正确的金额").show(); return false; } else { $("#txtTurnoverPerYear-error").text("").hide(); return true; } }
加载数据时再给数字分割逗号的使用:
$(function(){ joinMoney(); }) function joinMoney(){ var m = $.trim($("txtYearMoney").val()); $("txtYearMoney").val(joinVal(m)); }
24、自适应布局的写法
//方法一 绝对定位法 body{margin:0;padding:0;} .leftWrap1{width:200px;position: fixed;left:0;top:0;height:500px;background:#3c763d;} .mainWrap1{margin-left:200px;margin-right: 200px;height:500px;background: #dddddd;} .rightWrap1{width:200px;position: fixed;right:0;top:0;background: #5C6F85;height:500px;} <div class="leftWrap1"></div> <div class="mainWrap1"></div> <div class="rightWrap1"></div> //方法二 margin负值法,要注意的是主体内容层最外面要包含100%的大层 <div id="main"> <div id="body">222222222222</div> </div> <div id="left">22222222</div> <div id="right">33333333333</div> #main{width:100%;height:100%;float:left;} #left,#right{float: left;width:200px;height:100%;background: #5C6F85;} #body{margin:0 210px;height:100%;background: #3c763d;} #left{margin-left:-100%;} #right{margin-left:-200px;} // 方法三 自身浮动 <div class="left">222</div> <div class="right">111</div> <div class="main">333</div> .left{float:left;width:200px;height:500px;background: #5C6F85;} .right{float:right;width:200px;height:500px;background: #5C6F85;} .main{margin:0 210px;height:500px;background: #ddd;}
25、让已知宽高的弹窗居中
<div class="container"></div>
// css body{position: relative;} .container{width: 100px;height: 100px;border:1px solid #000000; position: absolute;margin: auto;left: 0;right: 0;top: 0;bottom: 0;} // js <script> $(function(){ $("body").width($(window).width()); $("body").height($(window).height()); }); </script>
关于粗心:
比如修改错误 添加和编辑界面是分为两个界面的情况,总是只改添加忘记改修改的
都说人不能两次踏进同一条河流,不能重复犯同样的错误,可是很多时候却老是重蹈覆辙
希望下来能细心点 做事或改问题时考虑全面些 确保正确
关于虚心接受批评:
做错事被叼很正常啊,心态要端正好,不要像小孩子一样被说一句就不高兴 了 被叼说明还有给你改正的机会
他们只是希望你做事更认真更细致一点 所以要平复心情虚心接受批评并且做好改正 才能进步
关于沟通:
问题讲清楚,分工也要考虑好如何分配,不要导致做白工,而且很关键的一点是 一定要坚持自己认为是对的 如果还有疑虑 就马上问清楚