在html中写的常用代码 图片,前端常用代码片段(一)

最后更新于2019年1月13日

前端常用代码片段(一) 点这里

前端常用代码片段(二) 点这里

前端常用代码片段(三) 点这里

前端常用代码片段(四) 点这里

前端常用代码片段(五) 点这里

前端常用代码片段(六) 点这里

1.回车触发事件的代码

$(function(){

$('#username').focus();

//回车查询

document.onkeydown = function(event) {

var e = event || window.event || arguments.callee.caller.arguments[0];

if (e && e.keyCode == 13) {

$("#signIn").trigger('click');

}

};

});

2.把对象格式的参数转成键值对,并以&分割

/**

* 把对象格式的参数转成键值对,并以&分割

* @param arr 要转换的对象参数

* @returns {string}

*/

function maiyaBuildParam(arr){

var result = '';

for(var key in arr)

{

result += key + "=" + encodeURIComponent(arr[key]) + "&";

}

result = result.substr(0,result.length-1);

return result;

}

3.去除表单内容两端的空格,设置cookie缓存,对象转成字符串

function submitForm() {

var param = {

userName: $.trim($("#username").val()),

password: $.trim($("#password").val())

//userName: $("#username").val().trim(),

//password: $("#password").val().trim()

//ie8下边支持$.trim, 不支持$("#").val().trim()

};

$.ajax({

type: "post",

url: serverIp + "rest/login?" + Math.random() + "&" + BuildParam(param),

//这里传入一个随机数避免ie8缓存问题,下边cache对ie8无效

//data: JSON.stringify(param), //传入组装的参数

//contentType: "application/json; charset=utf-8",

cache: false, //禁用缓存

dataType: "json",

success: function (result) {

if(result.result_code === '1'){

$.cookie('userinfo', JSON.stringify(result.data), { expires: 7 });

window.location.href = "index.html";

}else{

alert('用户名或密码错误');

}

},

error: function(msg) {

alert(msg.message || '操作失败!');

}

})

}

4.设置cookie,获取cookie

//设置cookie比,并将json数据源转成string

$.cookie('userinfo', JSON.stringify(json), { expires: 7 });

//获取cookie,并将返回的string格式数据解析成json

JSON.parse($.cookie('userinfo'));

//清除cookie

$.cookie('userinfo',null);

项目示例

//设置cookie

$.ajax({

type: "post",

url: serverIp + "rest/login?" + Math.random() + "&" + maiyaBuildParam(param),

dataType: "json",

success: function (result) {

if(result.result_code === '1'){

$.cookie('userinfo', JSON.stringify(result.data), { expires: 7 });

window.location.href = "index.html";

}else{

alert('用户名或密码错误');

}

},

error: function(msg) {

alert(msg.message || '操作失败!');

}

})

//获取和清空cookie

if(!$.cookie('userinfo')) {

location.href="login.html";

}

$("#loginOut a").click(function () {

$.cookie('userinfo',null);

});

var userinfo = JSON.parse($.cookie('userinfo'));

if(userinfo) {

var _src = userinfo.docPic ? userinfo.docPic : (userinfo.docSex == 2 ? 'images/women.png' : 'images/man.png');

$('#userInfoImage').attr("src",_src)

$('#username,#leftusername').html(userinfo.docName);

$('#jobtitle').html(userinfo.docProfe);

var docRole = userinfo.docRole == 0 && '医师' || '管理员';

$('#loginuser').html(docRole);

}

if(userinfo.docRole == 0) {

$('#menu-product').show();

$('#menu-admin,#menu-tongji').hide();

} else if(userinfo.docRole == 1) {

$('#menu-product').hide();

$('#menu-admin,#menu-tongji').show();

}

说明:

jquery.cookie.js 只允许开发人员存入字符串,故用JSON.stringify(json)将json转换成string

补充:JSON.stringify与JSON.parse() [ 此类方法在低版本ie上需要引入json2.js ]

parse用于从一个字符串中解析出json对象,如

var str = '{"name":"huangxiaojian","age":"23"}'

JSON.parse(str)

-->

Object

age: "23"

name: "huangxiaojian"

__proto__: Object

注意:单引号写在{}外,每个属性名都必须用双引号,否则会抛出异常。

stringify()用于从一个对象解析出字符串,如

var a = {a:1,b:2}

JSON.stringify(a)

--->

结果:"{"a":1,"b":2}"

5.三目运算的另一种写法

var docRole = userinfo.docRole == 0 && '医师' || '管理员';

var _src = userinfo.docPic ? userinfo.docPic : (userinfo.docSex == 2 ? 'images/women.png' : 'images/man.png');

记得以前看过别人写的文章里提到有网易的面试题出现过区分 || &&联合使用时返回的结果,当时老记不住,现在有这个应该容易记了

6.时间格式化

使用方式

new Date().format('yyyy-MM-dd'); // "2017-02-18"

new Date().format('yyyy-MM-dd hh-mm-ss'); //

"2017-02-18 04-41-08"

new Date().format('yyyy-MM-dd hh/mm/ss'); //

"2017-02-18 04/41/18"

new Date().format('yyyy-MM-dd HH/mm/ss'); //

"2017-02-18 16/42/30"

new Date().format('yyyy-MM-dd E HH/mm/ss');

//"2017-02-18 六 16/51/16"

new Date().format('yyyy-MM-dd EE HH/mm/ss'); //

"2017-02-18 周六 16/51/30"

new Date().format('yyyy-MM-dd EEE HH/mm/ss'); //

"2017-02-18 星期六 16/51/77"

源码

Date.prototype.format = function (fmt) {

var o = {

"M+": this.getMonth() + 1, //月份

"d+": this.getDate(), //日

"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //12小时

"H+": this.getHours(), //24小时

"m+": this.getMinutes(), //分

"s+": this.getSeconds(), //秒

"q+": Math.floor((this.getMonth() + 3) / 3), //季度

"S": this.getMilliseconds() //毫秒

};

var week = {

"0": "日",

"1": "一",

"2": "二",

"3": "三",

"4": "四",

"5": "五",

"6": "六"

};

if (/(y+)/.test(fmt)) {

fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

}

if (/(E+)/.test(fmt)) {

fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);

}

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;

}

7.获取输入日期所在周或者前后某周的周一

使用方式

new Date();

//Sat Feb 18 2017 17:35:25 GMT+0800 (中国标准时间)

getMonday( new Date(),-1); //

Mon Feb 06 2017 17:40:45 GMT+0800 (中国标准时间)

getMonday( new Date()); //Mon Feb 13 2017 17:34:34 GMT+0800 (中国标准时间)

getMonday( new Date(),1); //

Mon Feb 20 2017 17:34:43 GMT+0800 (中国标准时间)

源码

function getMonday(date, offset){

var today=date || new Date();

return new Date( today - ((today.getDay() ||7) -1 - (offset||0) *7 ) *864E5 );

}

//改进,获取输入日期所在周或者前后某周的任意某天

function getWeekAnyday(weekday,offset,date){

var today=date || new Date();

return new Date( today - ((today.getDay() ||7) -(weekday||0) - (offset||0) *7 ) *864E5 );

}

8.获取输入日期的前后某天日期

使用方式

new Date();

//Sat Feb 18 2017 17:35:25 GMT+0800 (中国标准时间)

getOneDayByDate(new Date() ,-2); //Thu Feb 16 2017 18:20:39 GMT+0800 (中国标准时间)

getOneDayByDate(new Date() ,2); //Mon Feb 20 2017 18:20:49 GMT+0800 (中国标准时间)

源码

function getOneDayByDate(date, n) {

var d = typeof date == 'string' && new Date(date) || date;

d.setTime(d.getTime()+24*60*60*1000*n);

//return d.getFullYear()+"-" + (d.getMonth()+1) + "-" + d.getDate(); //用于获取"2017-2-16"格式日期

return new Date(d);

}

9.My97DatePicker使用

首先引入js

场景1:选择时间段,前者不能大于后者的时间,后者不能小于前者时间且不大于当天时间

-

给input赋相差一个星期的初始值

$("#datemin").val(getOneDayByDate(new Date(), -6).format('yyyy-MM-dd'));

$("#datemax").val(thisDate());

function thisDate() {

var d = new Date();

return d.format('yyyy-MM-dd');

}

10.刷新当前页面

//刷新当前页面

location.reload();

//如果把该方法的参数设置为 true,那么无论文档的最后修改日期是什么,它都会绕过缓存,从服务器上重新下载该文档。这与用户在单击浏览器的刷新按钮时按住 Shift 健的效果是完全一样。

这是原生的方法

11. 判断元素是否在数组内

js方法

var arr = [1, 2, 3];

// js arr.indexOf(3)

var result1 = arr.indexOf(3); //返回index为2

jquery方法

var arr = [1, 2, 3];

// jquery $.inArray(3, arr)

var result = $.inArray(3, arr); //返回index为2

自定义方法

var arr = [1, 2, 3];

// 自定义 contains(arr, 3)方法

function contains(arr, obj) {

//while

var i = arr.length;

while(i--) {

if(arr[i] === obj) {

return i;

}

}

return -1;

}

var result1 = contains(arr, 3); //返回index为2

12.解析url中传递的参数

描述:解析ajax get方式传递的参数,

例如“https://www.zybuluo.com/mdedi...://www.zybuluo.com/static/editor/md-help.markdown”

1.方法一

使用方式

$.getUrlParam('url'); //"https://www.zybuluo.com/static/editor/md-help.markdown"

源码

$.getUrlParam = function(name) {

var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

var r = decodeURIComponent(window.location.search).substr(1).match(reg);

if (r!=null) return unescape(r[2]); return null;

};

说明:此方式是将方法拓展到了jquery,也可以定义成方法

使用方式

getUrlParam('url'); //"https://www.zybuluo.com/static/editor/md-help.markdown"

function getUrlParam(name) {

var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

var r = decodeURIComponent(window.location.search).substr(1).match(reg);

if (r!=null) return unescape(r[2]); return null;

};

2.方法二将携带的所有参数转化成json对象

使用方式

var urlParamsToJson= getUrlParamsToJson(); //Object {url: "https://www.zybuluo.com/static/editor/md-help.markdown"}

源码

function getUrlParamsToJson() {

var url = location.href;

var nameValue;

var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");

var paraObj = {};

for (var i = 0; nameValue = paraString[i]; i++) {

var name = nameValue.substring(0, nameValue.indexOf("=")).toLowerCase();

var value = nameValue.substring(nameValue.indexOf("=") + 1, nameValue.length);

if (value.indexOf("#") > -1) {

value = value.split("#")[0];

}

paraObj[name] = value;

}

return paraObj;

};

13.封装折叠(兼容ie8)

html

  • 标题+
    内容
    很多内容
  • 标题+
    2.png
  • 标题+
    1.png

css

.Huifold .item{ position:relative}

.Huifold .item h4{margin:0;font-weight:bold;position:relative;border-top: 1px solid #fff;font-size:15px;line-height:22px;padding:7px 10px;background-color:#eee;cursor:pointer;padding-right:30px}

.Huifold .item h4 b{position:absolute;display: block; cursor:pointer;right:10px;top:7px;width:16px;height:16px; text-align:center; color:#666}

.Huifold .item .info{display:none;padding:10px}

js

jQuery.Huifold = function (obj, obj_c, speed, obj_type, Event,selected) {

/*5个参数顺序不可打乱,分别是:相应区,隐藏显示的内容,速度,类型,事件*/

//1 只打开一个,可以全部关闭

//2 必须有一个打开

//3 可打开多个

//4全部打开

var selected = selected ||"selected";

if (obj_type == 2) {

$(obj + ":first").find("b").html("-");

$(obj_c + ":first").show();

}

if (obj_type == 4) {

$(obj).find("b").html("-");

$(obj_c).show();

}

if (obj_type == 5) {

$(obj).find("b").html("-");

$(obj_c).hide();

}

$(obj).on(Event, function () {

// console.log("11111");

if ($(this).next().is(":visible")) {

if (obj_type == 2) {

return false;

}

else {

$(this).next().slideUp(speed).end().removeClass(selected);

$(this).find("b").html("+");

}

}

else {

if (obj_type == 3 || obj_type == 4) {

$(this).next().slideDown(speed).end().addClass(selected);

$(this).find("b").html("-");

} else {

$(obj_c).slideUp(speed);

$(obj).removeClass(selected);

$(obj).find("b").html("+");

$(this).next().slideDown(speed).end().addClass(selected);

$(this).find("b").html("-");

}

}

});

};

调用

$(function(){

$.Huifold("#mealContainer>.item>.title", "#mealContainer>.item>.info", "fast", 4, "click");

});

14.封装tab页切换(兼容ie8)

html

选项卡一 选项卡二 自适应宽度
内容一
内容二
内容三

css

.clearfix:after{content:"\20";display:block;height:0;clear:both;visibility:hidden}.clearfix{zoom:1}

.tabBar {border-bottom: 2px solid #222}

.tabBar span {background-color: #e8e8e8;cursor: pointer;display: inline-block;float: left;font-weight: bold;height: 30px;line-height: 30px;padding: 0 15px}

.tabBar span.current{background-color: #222;color: #fff}

.tabCon {display: none}

js

jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i, callback) {

var $tab_menu = $(tabBar);

// 锟斤拷始锟斤拷锟斤拷锟斤拷

$tab_menu.removeClass(class_name);

$(tabBar).eq(i).addClass(class_name);

$(tabCon).hide();

$(tabCon).eq(i).show();

callback && callback(i);

$tab_menu.on(tabEvent, function (event) {

$tab_menu.removeClass(class_name);

$(this).addClass(class_name);

var index = $tab_menu.index(this).toString();

$(tabCon).hide();

$(tabCon).eq(index).show();

callback && callback(index);

event.stopPropagation();

});

};

调用

$(function(){

$.Huitab("#tabbarSonFirst>.tabBar span", "#tabbarSonFirst>.tabCon", "current", "click", "0", loadChart);

});

// #tabbarSonFirst 父级id

// #tabbarSonFirst>.tabBar span控制条

// #tabbarSonFirst>.tabCon内容区

// current 选中tab样式

// click 事件 点击切换,可以换成mousemove 移动鼠标切换

// 1 默认第2个tab为当前状态(从0开始)

// callback 实现选中后再加载函数

function loadChart(i) {

switch (i) {

case '0'

loopSportData();

break;

case '1'

loopMealData();

break;

case '2':

loadBloodPressureChart();

break;

default:

break;

}

}

15.正则校验Excel

var reg = /^.*\.(?:xls|xlsx)$/i;//文件名可以带空格

if (!reg.test(path)) {//校验不通过

alert("请上传excel格式的文件!");

return;

}

16.正则表达式 数字和字母组合且必须含有一个

$pattern = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/';

分开来注释一下:

^ 匹配一行的开头位置

(?![0-9]+$) 预测该位置后面不全是数字

(?![a-zA-Z]+$) 预测该位置后面不全是字母

[0-9A-Za-z] {6,10} 由6-10位数字或这字母组成

$ 匹配行结尾位置

17.低版本ie支持function.bind()

只需要添加一下代码,在需要的地方调用checkBind();就可以了

function checkBind()

{

if (!Function.prototype.bind) {

Function.prototype.bind = function(oThis) {

if (typeof this !== "function") {

throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");

}

var aArgs = Array.prototype.slice.call(arguments, 1),

fToBind = this,

fNOP = function() {},

fBound = function() {

return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,

aArgs.concat(Array.prototype.slice.call(arguments)));

};

fNOP.prototype = this.prototype;

fBound.prototype = new fNOP();

return fBound;

};

}

}

18.标题栏闪动提示

JS代码:

var titleInit = document.title, isShine = true;

setInterval(function() {

var title = document.title;

if (isShine == true) {

if (/新/.test(title) == false) {

document.title = '【你有新消息】';

} else {

document.title = '【     】';

}

} else {

document.title = titleInit;

}

}, 500);

window.onfocus = function() {

isShine = false;

};

window.onblur = function() {

isShine = true;

};

// for IE

document.onfocusin = function() {

isShine = false;

};

document.onfocusout = function() {

isShine = true;

};

19.img图片垂直居中

#box{

width:500px;height:400px;

text-align:center;

border:1px solid #d3d3d3;background:#fff;

display: table-cell;

vertical-align:middle;

}

#box img{

vertical-align:middle;

}

20.decodeURI() 函数解码处理不了"+"

使用javascript的decodeURIComponent函数解码查询字符串时,处理不了"+",例如下面

bVOMyP?w=610&h=290

这里需要再做一下处理:

decodeURIComponent(str.replace(/\+/g, '%20'));

即在调用decodeURIComponent函数之前要先把+替换为%20,这样就没有问题了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值