inchoong / go

短域名系统 ( https://go.choong.net/ )
15 stars 11 forks source link

前端开发常用代码片段 #7

Open taoste opened 4 years ago

taoste commented 4 years ago

Common-code 前端开发常用代码片段

一、预加载图像 如果你的网页中需要使用大量初始不可见的(例如,悬停的)图像,那么可以预加载这些图像。

$.preloadImages = function() { for (var i = 0; i < arguments.length; i++) { $("").attr("src", arguments[i]); } };

$.preloadImages("img/hover_on.png", "img/hover_off.png"); 二、检查图像是否加载 有时为了继续脚本,你可能需要检查图像是否全部加载完毕。

$("img").load(function() { console.log("image load successful"); }); 你也可以使用 ID 或 CLASS 替换 标签来检查某个特定的图像是否被加载。

三、自动修复破坏的图像 逐个替换已经破坏的图像链接是非常痛苦的。不过,下面这段简单的代码可以帮助你。

$("img").on("error", function() { if (!$(this).hasClass("on")) { $(this) .prop("src", "img/active.png") .addClass("on"); } }); 四、悬停切换 当用户鼠标悬停在可点击的元素上时,可添加类到元素中,反之则移除类。

$(el).hover( function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); } ); 只需要添加必要的 CSS 即可。更简单的方法是使用 toggleClass() 方法。

$(el).hover(function() { $(this).toggleClass("hover"); }); 五、淡入淡出/显示隐藏 // Fade $(".btn").click(function() { $(".el").fadeToggle("slow"); }); // Toggle $(".btn").click(function() { $(".el").slideToggle("slow"); }); 六、鼠标滚轮 $("#content").on("mousewheel DOMMouseScroll", function(event) { // chrome & ie || // firefox var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) || (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1));

if (delta > 0) { console.log("mousewheel top"); } else if (delta < 0) { console.log("mousewheel bottom"); } }); 七、鼠标坐标 1、JavaScript 实现 X: Y: function mousePosition(ev) { if (ev.pageX || ev.pageY) { return { x: ev.pageX, y: ev.pageY }; } return { x: ev.clientX + document.body.scrollLeft - document.body.clientLeft, y: ev.clientY + document.body.scrollTop - document.body.clientTop }; }

function mouseMove(ev) { ev = ev || window.event;

var mousePos = mousePosition(ev);

document.getElementById("xxx").value = mousePos.x; document.getElementById("yyy").value = mousePos.y; } document.onmousemove = mouseMove; 2、jQuery 实现 $("#ele").click(function(event) { //获取鼠标在图片上的坐标 console.log("X:" + event.offsetX + "\n Y:" + event.offsetY);

//获取元素相对于页面的坐标 console.log("X:" + $(this).offset().left + "\n Y:" + $(this).offset().top); }); 八、禁止移动端浏览器页面滚动 1、HTML 实现

2、JavaScript 实现 document.addEventListener("touchmove", function(event) { event.preventDefault(); }); 九、阻止默认行为 // JavaScript document.getElementById('btn').addEventListener('click', function (event) { event = event || window.event;

if (event.preventDefault){
    // W3C
    event.preventDefault();
} else{
    // IE
    event.returnValue = false;
}

}, false);

// jQuery $('#btn').on('click', function (event) { event.preventDefault(); }); 十、阻止冒泡 // JavaScript document.getElementById('btn').addEventListener('click', function (event) { event = event || window.event;

if (event.stopPropagation){
    // W3C
    event.stopPropagation();
} else{
    // IE
    event.cancelBubble = true;
}

}, false);

// jQuery $('#btn').on('click', function (event) { event.stopPropagation(); }); 十一、检测浏览器是否支持 svg function isSupportSVG() { var SVG_NS = "http://www.w3.org/2000/svg"; return ( !!document.createElementNS && !!document.createElementNS(SVG_NS, "svg").createSVGRect ); }

console.log(isSupportSVG()); 十二、检测浏览器是否支持 canvas function isSupportCanvas() { if (document.createElement("canvas").getContext) { return true; } else { return false; } }

console.log(isSupportCanvas()); 十三、检测是否是微信浏览器 function isWeiXinClient() { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == "micromessenger") { return true; } else { return false; } }

alert(isWeiXinClient()); 十四、检测是否移动端及浏览器内核 var browser = { versions: function() { var u = navigator.userAgent; return { trident: u.indexOf("Trident") > -1, //IE内核 presto: u.indexOf("Presto") > -1, //opera内核 webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核 gecko: u.indexOf("Firefox") > -1, //火狐内核Gecko mobile: !!u.match(/AppleWebKit.Mobile./), //是否移动终端 ios: !!u.match(/(i[^;]+;( U;)? CPU.+Mac OS X/), //ios android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android iPhone: u.indexOf("iPhone") > -1, //iPhone iPad: u.indexOf("iPad") > -1, //iPad webApp: u.indexOf("Safari") > -1 //Safari }; } };

if ( browser.versions.mobile() || browser.versions.ios() || browser.versions.android() || browser.versions.iPhone() || browser.versions.iPad() ){ alert("移动端"); } 十五、检测是否电脑端/移动端 var browser = { versions: (function() { var u = navigator.userAgent, app = navigator.appVersion; var sUserAgent = navigator.userAgent; return { trident: u.indexOf("Trident") > -1, presto: u.indexOf("Presto") > -1, isChrome: u.indexOf("chrome") > -1, isSafari: !u.indexOf("chrome") > -1 && /webkit|khtml/.test(u), isSafari3: !u.indexOf("chrome") > -1 && /webkit|khtml/.test(u) && u.indexOf("webkit/5") != -1, webKit: u.indexOf("AppleWebKit") > -1, gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, mobile: !!u.match(/AppleWebKit.Mobile./), ios: !!u.match(/(i[^;]+;( U;)? CPU.+Mac OS X/), android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, iPhone: u.indexOf("iPhone") > -1, iPad: u.indexOf("iPad") > -1, iWinPhone: u.indexOf("Windows Phone") > -1 }; })() }; if (browser.versions.mobile || browser.versions.iWinPhone) { window.location = "http:/www.baidu.com/m/"; } 十六、检测浏览器内核 function getInternet() { if (navigator.userAgent.indexOf("MSIE") > 0) { return "MSIE"; //IE浏览器 }

if ((isFirefox = navigator.userAgent.indexOf("Firefox") > 0)) { return "Firefox"; //Firefox浏览器 }

if ((isSafari = navigator.userAgent.indexOf("Safari") > 0)) { return "Safari"; //Safan浏览器 }

if ((isCamino = navigator.userAgent.indexOf("Camino") > 0)) { return "Camino"; //Camino浏览器 } if ((isMozilla = navigator.userAgent.indexOf("Gecko/") > 0)) { return "Gecko"; //Gecko浏览器 } } 十七、强制移动端页面横屏显示 $(window).on("orientationchange", function(event) { if (event.orientation == "portrait") { $("body").css("transform", "rotate(90deg)"); } else { $("body").css("transform", "rotate(0deg)"); } }); $(window).orientationchange(); 十八、电脑端页面全屏显示 function fullscreen(element) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } }

fullscreen(document.documentElement); 十九、获得/失去焦点 1、JavaScript 实现

// JavaScript window.onload = function() { var oIpt = document.getElementById("i_input");

if (oIpt.value == "会员卡号/手机号") { oIpt.style.color = "#888"; } else { oIpt.style.color = "#000"; }

oIpt.onfocus = function() { if (this.value == "会员卡号/手机号") { this.value = ""; this.style.color = "#000"; this.type = "password"; } else { this.style.color = "#000"; } };

oIpt.onblur = function() { if (this.value == "") { this.value = "会员卡号/手机号"; this.style.color = "#888"; this.type = "text"; } }; }; 2、jQuery 实现

<input type="password" name="psw" class="oldpsw" id="password" value="" style="display:none;" /> // jQuery $("#showPwd").focus(function() { var text_value = $(this).val(); if (text_value == "请输入您的注册密码") { $("#showPwd").hide(); $("#password") .show() .focus(); } }); $("#password").blur(function() { var text_value = $(this).val(); if (text_value == "") { $("#showPwd").show(); $("#password").hide(); } }); 二十、获取上传文件大小

// 兼容IE9低版本 function getFileSize(obj) { var filesize;

if (obj.files) { filesize = obj.files[0].size; } else { try { var path, fso; path = document.getElementById("filePath").value; fso = new ActiveXObject("Scripting.FileSystemObject"); filesize = fso.GetFile(path).size; } catch (e) { // 在IE9及低版本浏览器,如果不容许ActiveX控件与页面交互,点击了否,就无法获取size console.log(e.message); // Automation 服务器不能创建对象 filesize = "error"; // 无法获取 } } return filesize; } 二十一、限制上传文件类型 1、高版本浏览器

2、限制图片

3、低版本浏览器

/* 通过扩展名,检验文件格式。

  • @parma filePath{string} 文件路径
  • @parma acceptFormat{Array} 允许的文件类型
  • @result 返回值{Boolen}:true or false */

function checkFormat(filePath, acceptFormat) { var resultBool = false, ex = filePath.substring(filePath.lastIndexOf(".") + 1); ex = ex.toLowerCase();

for (var i = 0; i < acceptFormat.length; i++) { if (acceptFormat[i] == ex) { resultBool = true; break; } } return resultBool; }

function limitTypes() { var obj = document.getElementById("filePath"); var path = obj.value; var result = checkFormat(path, ["bmp", "jpg", "jpeg", "png"]);

if (!result) { alert("上传类型错误,请重新上传"); obj.value = ""; } } 二十二、正则表达式 //验证邮箱 /^\w+@([0-9a-zA-Z]+[.])+[a-z]{2,4}$/

//验证手机号 /^1[3|5|8|7]\d{9}$/

//验证URL /^http:\/\/.+./

//验证身份证号码 /(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/

//匹配字母、数字、中文字符 /^([A-Za-z0-9]|[\u4e00-\u9fa5])*$/

//匹配中文字符 /[\u4e00-\u9fa5]/

//匹配双字节字符(包括汉字) /[^\x00-\xff]/ 二十三、限制字符数

//字符串截取 function getByteVal(val, max) { var returnValue = ""; var byteValLen = 0; for (var i = 0; i < val.length; i++) { if (val[i].match(/[^\x00-\xff]/gi) != null) byteValLen += 2; else byteValLen += 1; if (byteValLen > max) break; returnValue += val[i]; } return returnValue; }

$("#txt").on("keyup", function() { var val = this.value; if (val.replace(/[^\x00-\xff]/g, "**").length > 14) { this.value = getByteVal(val, 14); } }); 二十四、验证码倒计时

// JavaScript var times = 60, // 时间设置60秒 timer = null;

document.getElementById("send").onclick = function() { // 计时开始 timer = setInterval(function() { times--;

if (times <= 0) {
  send.value = "发送验证码";
  clearInterval(timer);
  send.disabled = false;
  times = 60;
} else {
  send.value = times + "秒后重试";
  send.disabled = true;
}

}, 1000); }; var times = 60, timer = null;

$('#send').on('click', function () { var $this = $(this);

// 计时开始
timer = setInterval(function () {
    times--;

    if (times <= 0) {
        $this.val('发送验证码');
        clearInterval(timer);
        $this.attr('disabled', false);
        times = 60;
    } else {
        $this.val(times + '秒后重试');
        $this.attr('disabled', true);
    }
}, 1000);

}); 二十五、时间倒计时

function countdown() { var endtime = new Date("May 2, 2018 21:31:09"); var nowtime = new Date();

if (nowtime >= endtime) { document.getElementById("_lefttime").innerHTML = "倒计时间结束"; return; }

var leftsecond = parseInt((endtime.getTime() - nowtime.getTime()) / 1000); if (leftsecond < 0) { leftsecond = 0; }

d = parseInt(leftsecond / 3600 / 24); h = parseInt((leftsecond / 3600) % 24); m = parseInt((leftsecond / 60) % 60); s = parseInt(leftsecond % 60);

document.getElementById("_lefttime").innerHTML = d + "天" + h + "小时" + m + "分" + s + "秒"; }

countdown();

setInterval(countdown, 1000); 二十六、倒计时跳转

// 设置倒计时秒数 var t = 10;

// 显示倒计时秒数 function showTime() { t -= 1; document.getElementById("showtimes").innerHTML = t;

if (t == 0) { location.href = "error404.asp"; }

//每秒执行一次 showTime() setTimeout("showTime()", 1000); }

showTime(); 二十七、时间戳、毫秒格式化 function formatDate(now) { var y = now.getFullYear(); var m = now.getMonth() + 1; // 注意 JavaScript 月份+1 var d = now.getDate(); var h = now.getHours(); var m = now.getMinutes(); var s = now.getSeconds();

return y + "-" + m + "-" + d + " " + h + ":" + m + ":" + s; }

var nowDate = new Date(1442978789184);

alert(formatDate(nowDate)); 二十八、当前日期 var calculateDate = function() { var date = new Date(); var weeks = ["日", "一", "二", "三", "四", "五", "六"];

return ( date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日 星期" + weeks[date.getDay()] ); };

$(function() { $("#dateSpan").html(calculateDate()); }); 二十九、判断周六/周日

function time(y, m) { var tempTime = new Date(y, m, 0); var time = new Date(); var saturday = new Array(); var sunday = new Array();

for (var i = 1; i <= tempTime.getDate(); i++) { time.setFullYear(y, m - 1, i);

var day = time.getDay();

if (day == 6) {
  saturday.push(i);
} else if (day == 0) {
  sunday.push(i);
}

}

var text = y + "年" + m + "月份" + "
" + "周六:" + saturday.toString() + "
" + "周日:" + sunday.toString();

document.getElementById("text").innerHTML = text; }

time(2018, 5); 三十、AJAX 调用错误处理 当 Ajax 调用返回 404 或 500 错误时,就执行错误处理程序。如果没有定义处理程序,其他的 jQuery 代码或会就此罢工。定义一个全局的 Ajax 错误处理程序

$(document).ajaxError(function(e, xhr, settings, error) { console.log(error); }); 三十一、链式插件调用 jQuery 允许“链式”插件的方法调用,以减轻反复查询 DOM 并创建多个 jQuery 对象的过程。

$("#el").show(); $("#el").html("on"); $("#el").otherStuff(); 通过使用链式,可以改善

$("#el").show().html("on").otherStuff(); 还有一种方法是在(前缀$)变量中高速缓存元素

var $el = $("#el"); $el.hide(); $el.html("on"); $el.otherStuff(); 链式和高速缓存的方法都是 jQuery 中可以让代码变得更短和更快的最佳做法。

三十二、IE 条件注释 条件注释简介 IE 中的条件注释(Conditional comments)对 IE 的版本和 IE 非 IE 有优秀的区分能力,是 WEB 设计中常用的 hack 方法。 条件注释只能用于 IE5 以上,IE10 以上不支持。

如果你安装了多个 IE,条件注释将会以最高版本的 IE 为标准。

条件注释的基本结构和 HTML 的注释(<!– –>)是一样的。因此 IE 以外的浏览器将会把它们看作是普通的注释而完全忽略它们。

IE 将会根据 if 条件来判断是否如解析普通的页面内容一样解析条件注释里的内容。

条件注释使用方法示例 <!–-[if IE 5]>仅IE5.5可见<![endif]–-> <!–-[if gt IE 5.5]>仅IE 5.5以上可见<![endif]–-> <!–-[if lt IE 5.5]>仅IE 5.5以下可见<![endif]–-> <!–-[if gte IE 5.5]>IE 5.5及以上可见<![endif]–-> <!–-[if lte IE 5.5]>IE 5.5及以下可见<![endif]–-> <!–-[if !IE 5.5]>非IE 5.5的IE可见<![endif]–-> 三十三、html 代码用 js 动态加载进页面

把上面的 js 动态加入到页面中

$(function() { var s = $("#T-pcList").html(); //获得js的html内容 $(".picScroll-left .bd").html(s); //把s的内容放到class为bd内 thisstyle(); //执行某个函数 }); 三十四、设置获取cookie //方式1 //设置cookie //两个参数,一个是cookie的名字,一个是值 function SetCookie(name, value) { var Days = 30; //此 cookie 将被保存 30 天 var exp = new Date(); //new Date("December 31, 9998"); exp.setTime(exp.getTime() + Days 24 60 60 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); } //读取cookies function GetCookie(name) { var arr = document.cookie.match( new RegExp("(^| )" + name + "=([^;]*)(;|$)") ); if (arr != null) return unescape(arr[2]); return null; } //删除cookies function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } 三十五、银行卡号每四位补空格 //银行卡号按4位一空格显示(使用 onkeyup(setBankNoStyle(this.value))) function setBankNoStyle(BankNo) { var lKeyCode = navigator.appname == "Netscape" ? event.which : event.keyCode; if (lKeyCode != 8) { if (BankNo.value == "") return; var account = new String(BankNo.value).replace(/\s/g, ""); var strTemp = ""; for (var i = 0; i < account.length; i++) { if (!isNaN(account[i])) { strTemp = strTemp + account[i]; } } var strValue = strTemp.substr(0, 19); strTemp = ""; for (var j = 0; j < strValue.length; j++) { if ((j + 1) % 4 == 0) { strTemp = strTemp + strValue[j] + " "; } else { strTemp = strTemp + strValue[j]; } } $(BankNo).val(strTemp); } } 三十六、JS,Jquery 获取各种屏幕的宽度和高度 js //文档可视区域宽: document.documentElement.clientWidth //文档可视区域高: document.documentElement.clientHeight //网页可见区域宽: document.body.clientWidth //网页可见区域高: document.body.clientHeight //网页可见区域宽: (包括边线的宽) document.body.offsetWidth //网页可见区域高: (包括边线的高) document.body.offsetHeight //网页正文全文宽: document.body.scrollWidth //网页正文全文高: document.body.scrollHeight //网页被卷去的高: document.body.scrollTop //网页被卷去的左: document.body.scrollLeft //网页正文部分上: window.screenTop //网页正文部分左: window.screenLeft //屏幕分辨率的高: window.screen.height //屏幕分辨率的宽: window.screen.width //屏幕可用工作区高度: window.screen.availHeight //屏幕可用工作区宽度: window.screen.availWidth JQuery alert(window.height()); //浏览器当前窗口可视区域高度 alert(document.height()); //浏览器当前窗口文档的高度alert((document.body).height());//浏览器当前窗口文档body的高度 alert($(document.body).outerHeight(true)); //浏览器当前窗口文档body的总高度 包括border padding margin alert(window.width()); //浏览器当前窗口可视区域宽度alert((document).width());//浏览器当前窗口文档对象宽度 alert(document.body.width()); //浏览器当前窗口文档body的宽度alert((document.body).outerWidth(true));//浏览器当前窗口文档body的总宽度 包括border padding margin 三十七、jquery 对文本框只读状态与可读状态的相互转化 $("input").removeAttr("Readonly"); $("input").attr("Readonly", "true"); 三十八、js/jquery 实现密码框输入聚焦,失焦问题 js 实现方法 html 代码:

js 代码:

window.onload = function() { var oIpt = document.getElementById("i_input"); if (oIpt.value == "会员卡号/手机号") { oIpt.style.color = "#888"; } else { oIpt.style.color = "#000"; } oIpt.onfocus = function() { if (this.value == "会员卡号/手机号") { this.value = ""; this.style.color = "#000"; this.type = "password"; } else { this.style.color = "#000"; } }; oIpt.onblur = function() { if (this.value == "") { this.value = "会员卡号/手机号"; this.style.color = "#888"; this.type = "text"; } }; }; jquery 实现方法 html 代码:

<input type="password" name="psw" class="oldpsw" id="password" value="" style="display:none;" /> jquery 代码:

$("#showPwd").focus(function() { var text_value = $(this).val(); if (text_value == "请输入您的注册密码") { $("#showPwd").hide(); $("#password") .show() .focus(); } }); $("#password").blur(function() { var text_value = $(this).val(); if (text_value == "") { $("#showPwd").show(); $("#password").hide(); } }); 三十九、获取当前日期

var calculateDate = function() { var date = new Date(); var weeks = ["日", "一", "二", "三", "四", "五", "六"]; return ( date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日 星期" + weeks[date.getDay()] ); };

$(function() { $("#dateSpan").html(calculateDate()); }); 四十、时间倒计时(固定倒计时的结束时间) function countdown() { var endtime = new Date("Jan 18, 2015 23:50:00"); var nowtime = new Date(); if (nowtime >= endtime) { document.getElementById("_lefttime").innerHTML = "倒计时间结束"; return; } var leftsecond = parseInt((endtime.getTime() - nowtime.getTime()) / 1000); if (leftsecond < 0) { leftsecond = 0; } d = parseInt(leftsecond / 3600 / 24); h = parseInt((leftsecond / 3600) % 24); m = parseInt((leftsecond / 60) % 60); s = parseInt(leftsecond % 60); document.getElementById("_lefttime").innerHTML = d + "天" + h + "小时" + m + "分" + s + "秒"; }

countdown(); setInterval(countdown, 1000); 四十一、10 秒倒计时跳转

//设定倒数秒数 var t = 10; //显示倒数秒数 function showTime() { t -= 1; document.getElementById("showtimes").innerHTML = t; if (t == 0) { location.href = "error404.asp"; } //每秒执行一次,showTime() setTimeout("showTime()", 1000); } //执行showTime() showTime(); 四十二、判断浏览器的简单有效方法 function getInternet() { if (navigator.userAgent.indexOf("MSIE") > 0) { return "MSIE"; //IE浏览器 }

if ((isFirefox = navigator.userAgent.indexOf("Firefox") > 0)) { return "Firefox"; //Firefox浏览器 }

if ((isSafari = navigator.userAgent.indexOf("Safari") > 0)) { return "Safari"; //Safan浏览器 }

if ((isCamino = navigator.userAgent.indexOf("Camino") > 0)) { return "Camino"; //Camino浏览器 } if ((isMozilla = navigator.userAgent.indexOf("Gecko/") > 0)) { return "Gecko"; //Gecko浏览器 } } 四十三、每隔 0.1s 改变图片的路径 html

js

(function() { function chagesimagesrc(t) { document.getElementById("tt").childNodes[0].src = "images/" + t + ".jpg"; } setInterval(function() { for (var i = 0; i < 2; i++) { setTimeout( (function(t) { return function() { chagesimagesrc(t); }; })(i + 1), i * 100 ); } }, 1000); })(); 四十四、点击某个 div 区域之外,隐藏该 div 一般写法:

$(document).on("click", function(e) { var target = $(e.target); if (target.closest(".city_box,#city_select a.selected").length == 0) { $(".city_box").hide(); } }); 更全的方式:

$(document).click(function(e){ var _con = $(' 目标区域 '); // 设置目标区域 if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1 some code... // 功能代码 } }); /* Mark 1 的原理: 判断点击事件发生在区域外的条件是:

  1. 点击事件的对象不是目标区域本身
  2. 事件对象同时也不是目标区域的子元素 */ 四十五、全局处理null值或者''的函数,如果为null或者''返回-。如果传入第二个参数,表示截取指定长度的字符串 /**
    • 一个值如果是null或者''返回-
    • @param value 需要处理的值
    • @param length 需要截取的字符的长度的值,未指定的时候返回全部
    • @returns {} 处理过的值 / function replaceNull(value, length) { //判断截取的值是否为空 if ( value == null || value == undefined || value == "" || value == "undefined" ) { return "-"; } //判断长度是否为空 if (length == null || length == "") { return value; } return value.toString().substr(0, length); } 四十六、如何在手机上禁止浏览器的网页滚动 方法一:

方法二:

document.addEventListener("touchmove", function(event) { event.preventDefault(); }); 四十七、改变 type=file 默认样式,"浏览"等字体

四十八、js 判断变量是否未定义的代码 //一般如果变量通过var声明,但是并未初始化的时候,变量的值为undefined,而未定义的变量则需要通过 "typeof 变量"的形式来判断,否则会发生错误。 //实际应用:variable有的页面我们不定义,但有的页面定义了,就可以需要这样的判断方法,没有定义的就不执行。

if ("undefined" != typeof variable) { if (variable == "abc") { console.log("成功"); } } 四十九、针对 IE6,7 的 hack,该怎么写 你可能会这么回答:使用 “>”,“_”,“*”等各种各样的符号来写 hack。是的,这样做没错,但是需要记住每个符号分别被哪些浏览器识别,并且如果写的太乱将造成代码 阅读起来十分困难。学习 CSS 必须抱有一种质疑精神,有没有一种 hack 方法可以不写这些乱七八糟的符号,并且代码易维护易读呢?我们可以看看好搜首页是怎么做的:在页面顶端有这样一句话:

<!DOCTYPE html>

在页面的 CSS 中,会看到这样的规则: .ie7 #hd_usernav:before, .ie8 #hd_usernav:before { display: none; } .ie6 .skin_no #hd_nav li, .ie7 .skin_no #hd_nav li, .ie8 .skin_no #hd_nav li { border-right-color: #c5c5c5; } .ie6 .skin_no #hd_nav a, .ie7 .skin_no #hd_nav a, .ie8 .skin_no #hd_nav a { color: #c5c5c5; } 五十、js 动态创建 css 样式添加到 head 内 function addCSS(cssText) { var style = document.createElement("style"); var head = document.head || document.getElementsByTagName("head")[0]; style.type = "text/css"; if (style.styleSheet) { //IE var func = function() { try { //防止IE中stylesheet数量超过限制而发生错误 style.styleSheet.cssText = cssText; } catch (e) {} }; //如果当前styleSheet还不能用,则放到异步中则行 if (style.styleSheet.disabled) { setTimeout(func, 10); } else { func(); } } else { //w3c //w3c浏览器中只要创建文本节点插入到style元素中就行了 var textNode = document.createTextNode(cssText); style.appendChild(textNode); } //把创建的style元素插入到head中 head.appendChild(style); } //使用 addCSS("#demo{ height: 30px; background:#f00;}"); 在 IE8 以及其低版本浏览器下,IE 独有属性 styleSheet.cssText。所以一般的兼容简单写法: var style = document.createElement("style"); style.type = "text/css"; if (style.styleSheet) { //IE style.styleSheet.cssText = "/*..css content here..*/"; } else { //w3c style.innerHTML = "/*..css content here..*/"; } document.getElementsByTagName("head")[0].appendChild(style); 五十一、form 表单提交时设置编码格式
//内容
五十二、js 加入收藏代码 function addFavorite(title, url) { url = encodeURI(url); try { window.external.addFavorite(url, title); } catch (e) { try { window.sidebar.addPanel(title, url, ""); } catch (e) { alert("加入收藏失败,Ctrl+D进行添加"); } } } // 调用 addFavorite(document.title, window.location); 打印方法:(整个页面 window.print()) //id-str 内容中的id function Printpart(id_str) { var el = document.getElementById(id_str); var iframe = document.createElement("IFRAME"); var doc = null; iframe.setAttribute( "style", "position:absolute;width:0px;height:0px;left:-500px;top:-500px;" ); document.body.appendChild(iframe); doc = iframe.contentWindow.document; doc.write("
" + el.innerHTML + "
"); doc.close(); iframe.contentWindow.focus(); iframe.contentWindow.print(); if (navigator.userAgent.indexOf("MSIE") > 0) { document.body.removeChild(iframe); } } 五十三、js 强制手机页面横屏显示 $(window).on("orientationchange", function(event) { if (event.orientation == "portrait") { $("body").css("transform", "rotate(90deg)"); } else { $("body").css("transform", "rotate(0deg)"); } }); $(window).orientationchange(); 五十四、js 强制手机页面横屏显示 jquery 获得 select 中 option 的索引 html 代码: jquery 代码: $(".select-green").change(function() { var _indx = $(this).get(0).selectedIndex; $(".selectall .selectCon").hide(); $(".selectall .selectCon") .eq(_indx) .fadeIn(); }); // 注:其中(this).get(0)与(this)[0]等价 五十五、获取上传文件的大小 html 代码: js 代码: //兼容IE9低版本获取文件的大小 function getFileSize(obj) { var filesize; if (obj.files) { filesize = obj.files[0].size; } else { try { var path, fso; path = document.getElementById("filePath").value; fso = new ActiveXObject("Scripting.FileSystemObject"); filesize = fso.GetFile(path).size; } catch (e) { //在IE9及低版本浏览器,如果不容许ActiveX控件与页面交互,点击了否,就无法获取size console.log(e.message); //Automation 服务器不能创建对象 filesize = "error"; //无法获取 } } return filesize; } 五十六、限制上传文件的类型 如果是高版本浏览器,一般在 HTML 代码中写就能实现,如: `` 如果限制上传文件为图片类型,如下: ```html 但是在其它低版本浏览器就不管用了,需要 js 来判断。 html 代码: js 代码: /* 通过扩展名,检验文件格式。 *@parma filePath{string} 文件路径 *@parma acceptFormat{Array} 允许的文件类型 *@result 返回值{Boolen}:true or false */ function checkFormat(filePath, acceptFormat) { var resultBool = false, ex = filePath.substring(filePath.lastIndexOf(".") + 1); ex = ex.toLowerCase(); for (var i = 0; i < acceptFormat.length; i++) { if (acceptFormat[i] == ex) { resultBool = true; break; } } return resultBool; } function limitTypes() { var obj = document.getElementById("filePath"); var path = obj.value; var result = checkFormat(path, ["bmp", "jpg", "jpeg", "png"]); if (!result) { alert("上传类型错误,请重新上传"); obj.value = ""; } } 五十七、随机产生 lowwer - upper 之间的随机数 function selectFrom(lower, upper) { var sum = upper - lower + 1; //总数-第一个数+1 return Math.floor(Math.random() * sum + lower); } 五十八、跨浏览器添加事件 //跨浏览器添加事件 function addEvent(obj, type, fn) { if (obj.addEventListener) { obj.addEventListener(type, fn, false); } else if (obj.attachEvent) { //IE obj.attchEvent("on" + type, fn); } } 五十九、跨浏览器移除事件 //跨浏览器移除事件 function removeEvent(obj, type, fn) { if (obj.removeEventListener) { obj.removeEventListener(type, fn, false); } else if (obj.detachEvent) { //兼容IE obj.detachEvent("on" + type, fn); } } 六十、跨浏览器阻止默认行为 //跨浏览器阻止默认行为 function preDef(ev) { var e = ev || window.event; if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } 六十一、跨浏览器获取目标对象 //跨浏览器获取目标对象 function getTarget(ev) { if (ev.target) { //w3c return ev.target; } else if (window.event.srcElement) { //IE return window.event.srcElement; } } 六十二、跨浏览器获取滚动条位置 //跨浏览器获取滚动条位置,sp == scroll position function getSP(){ return{ top: document.documentElement.scrollTop || document.body.scrollTop, left : document.documentElement.scrollLeft || document.body.scrollLeft; } } 六十三、跨浏览器获取可视窗口大小 //跨浏览器获取可视窗口大小 function getWindow() { if (typeof window.innerWidth != "undefined") { return { width: window.innerWidth, height: window.innerHeight }; } else { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; } } 六十四、js 对象冒充 function Person(name, age) { this.name = name; this.age = age; this.say = function() { return "name : " + this.name + " age: " + this.age; }; } var o = new Object(); //可以简化为Object() Person.call(o, "zhangsan", 20); console.log(o.say()); //name : zhangsan age: 20 六十五、js 异步加载和同步加载 异步加载也叫非阻塞模式加载,浏览器在下载 js 的同时,同时还会执行后续的页面处理。 在 script 标签内,用 js 创建一个 script 元素并插入到 document 中,这种就是异步加载 js 文件了: (function() { var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = "http://yourdomain.com/script.js"; var x = document.getElementsByTagName("script")[0]; x.parentNode.insertBefore(s, x); })(); 同步加载 平常默认用的都是同步加载。如: X: Y: DTD 已声明的情况下: 如果在页面中添加这行标记的话 IE document.body.clientWidth //==> BODY对象/宽度 document.body.clientHeight //==> BODY对象高度 document.documentElement.clientWidth //==> 可见区域宽度 document.documentElement.clientHeight //==> 可见区域高度 Firefox document.documentElement.scrollHeight //==> 浏览器所有内容高度 document.body.scrollHeight //==> 浏览器所有内容高度 document.documentElement.scrollTop //==> 浏览器滚动部分高度 document.body.scrollTop //==>始终为0 document.documentElement.clientHeight //==>浏览器可视部分高度 document.body.clientHeight //==> 浏览器所有内容高度 Chrome document.documentElement.scrollHeight //==> 浏览器所有内容高度 document.body.scrollHeight //==> 浏览器所有内容高度 document.documentElement.scrollTop //==> 始终为0 document.body.scrollTop //==>浏览器滚动部分高度 document.documentElement.clientHeight //==> 浏览器可视部分高度 document.body.clientHeight //==> 浏览器所有内容高度 浏览器所有内容高度即浏览器整个框架的高度,包括滚动条卷去部分+可视部分+底部隐藏部分的高度总和 浏览器滚动部分高度即滚动条卷去部分高度即可视顶端距离整个对象顶端的高度。 综上 1、document.documentElement.scrollTop 和 document.body.scrollTop 始终有一个为 0,所以可以用这两个的和来求 scrollTop 2、scrollHeight、clientHeight 在 DTD 已声明的情况下用 documentElement,未声明的情况下用 body clientHeight 在 IE 和 FF 下,该属性没什么差别,都是指浏览器的可视区域,即除去浏览器的那些工具栏状态栏剩下的页面展示空间的高度。 六十七、js 拖拽效果
六十八、判断设备跳转不同平台 function PCjudgment(mobile, pc) { var UserClient = navigator.userAgent.toLowerCase(); var IsIPad = UserClient.match(/ipad/i) == "ipad"; var IsIphoneOs = UserClient.match(/iphone os/i) == "iphone os"; var IsMidp = UserClient.match(/midp/i) == "midp"; var IsUc7 = UserClient.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; var IsUc = UserClient.match(/ucweb/i) == "ucweb"; var IsAndroid = UserClient.match(/android/i) == "android"; var IsCE = UserClient.match(/windows ce/i) == "windows ce"; var IsWM = UserClient.match(/windows mobile/i) == "windows mobile"; if ( IsIPad || IsIphoneOs || IsMidp || IsUc7 || IsUc || IsAndroid || IsCE || IsWM ) { window.location = mobile; } else { window.location = pc; } } 六十九、获取地址栏参数 function getParameter(param) { var query = window.location.search; // 获取URL地址中?后的所有字符 var iLen = param.length; // 获取你的参数名称长度 var iStart = query.indexOf(param); // 获取你该参数名称的其实索引 if (iStart == -1) // -1为没有该参数 return ""; iStart += iLen + 1; var iEnd = query.indexOf("&", iStart); // 获取第二个参数的其实索引 if (iEnd == -1) // 只有一个参数 return query.substring(iStart); // 获取单个参数的参数值 return query.substring(iStart, iEnd); // 获取第二个参数的值 } 七十、获取全部 url 参数,并转换成 json 对象 function getUrlAllParams(url) { var url = url ? url : window.location.href; var _pa = url.substring(url.indexOf("?") + 1), _arrS = _pa.split("&"), _rs = {}; for (var i = 0, _len = _arrS.length; i < _len; i++) { var pos = _arrS[i].indexOf("="); if (pos == -1) { continue; } var name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1)); _rs[name] = value; } return _rs; } 七十一、删除 url 指定参数,返回 url delParamsUrl(window.location.href,"a") function delParamsUrl(url, name) { var baseUrl = url.split("?")[0] + "?"; var query = url.split("?")[1]; if (query.indexOf(name) > -1) { var obj = {}; var arr = query.split("&"); for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].split("="); obj[arr[i][0]] = arr[i][1]; } delete obj[name]; var url = baseUrl + JSON.stringify(obj) .replace(/[\"\{\}]/g, "") .replace(/\:/g, "=") .replace(/\,/g, "&"); return url; } else { return url; } } 七十二、加入收藏夹 function AddFavorite(sURL, sTitle) { try { window.external.addFavorite(sURL, sTitle); } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, ""); } catch (e) { alert("加入收藏失败,请使用Ctrl+D进行添加"); } } } 七十三、设为首页 function setHomepage(homeUrl) { if (document.all) { document.body.style.behavior = "url(#default#homepage)"; document.body.setHomePage(homeUrl); } else { alert("浏览器不支持此操作, 请手动设为首页"); } } 七十四、返回顶部 function goTop() { $(window).scroll(function() { var a = $(window).scrollTop(); if (a > 100) { $(".go-top").fadeIn(); } else { $(".go-top").fadeOut(); } }); $(".go-top").click(function() { $("html,body").animate( { scrollTop: "0px" }, "600" ); }); } 七十五、保存到桌面 function toDesktop(sUrl, sName) { try { var WshShell = new ActiveXObject("WScript.Shell"); var oUrlLink = WshShell.CreateShortcut( WshShell.SpecialFolders("Desktop") + "\\" + sName + ".url" ); oUrlLink.TargetPath = sUrl; oUrlLink.Save(); } catch (e) { alert("当前IE安全级别不允许操作!"); } } 七十六、删除数组中存在重复的元素,去重 function getUnique(someArray) { tempArray = someArray.slice(0); //复制数组到临时数组 for (var i = 0; i < tempArray.length; i++) { for (var j = i + 1; j < tempArray.length; ) { if (tempArray[j] == tempArray[i]) { //后面的元素若和待比较的相同,则删除并计数; //删除后,后面的元素会自动提前,所以指针j不移动 tempArray.splice(j, 1); } else { j++; } //不同,则指针移动 } } return tempArray; } 七十七、使用方法:Ajax('/data.json', 'get', function (data) { console.log(data); }); function Ajax(url, type, success, error) { $.ajax({ type: type, url: url, dataType: "jsonp", crossDomain: true, async: false, success: function(res) { var data = res.data; success && success(data); }, error: function(e) { error && error(e); } }); } 七十八、阻止冒泡 function stopBubble(e) { e = e || window.event; if (e.stopPropagation) { e.stopPropagation(); //W3C阻止冒泡方法 } else { e.cancelBubble = true; //IE阻止冒泡方法 } } 七十九、13 位时间戳转日期 1970/01/19 4:12 function getLocalTime(nS) { //return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/,' '); var date = new Date(nS); var Y = date.getFullYear() + "/"; var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "/"; var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "; var h = date.getHours() + ":"; var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + " "; //var s = date.getSeconds(); return Y + M + D + h + m; } 八十、去除空格 // type 1-所有空格 2-前后空格 3-前空格 4-后空格 function trim(str, type) { switch (type) { case 1: return str.replace(/\s+/g, ""); case 2: return str.replace(/(^\s*)|(\s*$)/g, ""); case 3: return str.replace(/(^\s*)/g, ""); case 4: return str.replace(/(\s*$)/g, ""); default: return str; } } 八十一、type 1:首字母大写 2:首页母小写 3:大小写转换 4:全部大写 5:全部小写 //changeCase('asdasd',1) => Asdasd function changeCase(str, type) { function ToggleCase(str) { var itemText = ""; str.split("").forEach(function(item) { if (/^([a-z]+)/.test(item)) { itemText += item.toUpperCase(); } else if (/^([A-Z]+)/.test(item)) { itemText += item.toLowerCase(); } else { itemText += item; } }); return itemText; } switch (type) { case 1: return str.replace(/^(\w)(\w+)/, function(v, v1, v2) { return v1.toUpperCase() + v2.toLowerCase(); }); case 2: return str.replace(/^(\w)(\w+)/, function(v, v1, v2) { return v1.toLowerCase() + v2.toUpperCase(); }); case 3: return ToggleCase(str); case 4: return str.toUpperCase(); case 5: return str.toLowerCase(); default: return str; } } 八十二、判断是否是一个数组 isArray([1,2,3]) //true function isArray(arr) { return Object.prototype.toString.call(arr) === "[object Array]"; } 八十三、判断是否是一个函数(三种) function isFunction(fn) { return Object.prototype.toString.call(fn) === "[object Function]"; return fn.constructor == Function; return fn instanceof Function; return typeof fn == Function; } 八十四、判断是否为邮箱地址 isEmail("1025554991@qq.com") function isEmail(emailStr) { var reg = /^[a-zA-Z0-9]+([._-]*[a-zA-Z0-9]*)*@[a-zA-Z0-9]+.[a-zA-Z0-9{2,5}$]/; var result = reg.test(emailStr); if (result) { return true; } else { return false; } } 八十五、判断是否是手机号 function isPoneAvailable(str) { var myreg = /^[1][3,4,5,7,8][0-9]{9}$/; if (!myreg.test(str)) { return false; } else { return true; } } 八十六、转换手机号码中间四位为* function transPhone(val) { return val.substring(0, 3) + "****" + val.substring(7, 11); } 八十七、身份证号码 // 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X // 严格的身份证校验 function isCardID(sId) { if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) { alert("你输入的身份证长度或格式错误"); return false; } //身份证城市 var aCity = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" }; if (!aCity[parseInt(sId.substr(0, 2))]) { alert("你的身份证地区非法"); return false; } // 出生日期验证 var sBirthday = ( sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2)) ).replace(/-/g, "/"), d = new Date(sBirthday); if ( sBirthday != d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() ) { alert("身份证上的出生日期非法"); return false; } // 身份证号码校验 var sum = 0, weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], codes = "10X98765432"; for (var i = 0; i < sId.length - 1; i++) { sum += sId[i] * weights[i]; } var last = codes[sum % 11]; //计算出来的最后一位身份证号码 if (sId[sId.length - 1] != last) { alert("你输入的身份证号非法"); return false; } return true; } 八十八、真实姓名 function isName() { var regName = /^[\u4e00-\u9fa5]{2,4}$/; if (!regName.test(isName)) { alert("真实姓名填写有误"); return false; } } 八十九、json数组去重 function UniquePay(paylist) { var payArr = [paylist[0]]; for (var i = 1; i < paylist.length; i++) { var payItem = paylist[i]; var repeat = false; for (var j = 0; j < payArr.length; j++) { if (payItem.name == payArr[j].name) { repeat = true; break; } } if (!repeat) { payArr.push(payItem); } } return payArr; } 九十、对比两个数组,取出交集 // 对比两个数组, 取出交集 console.log(intersect(["1","2", "3"], ["2","3", "4", "5", "6"])) function intersect() { var result = new Array(); var obj = {}; for (var i = 0; i < arguments.length; i++) { for (var j = 0; j < arguments[i].length; j++) { var str = arguments[i][j]; if (!obj[str]) { obj[str] = 1; } else { obj[str]++; if (obj[str] == arguments.length) { result.push(str); } } //end else } //end for j } //end for i return result; } 九十一、动态加载 CSS 文件 function LoadStyle(url) { try { document.createStyleSheet(url); } catch (e) { var cssLink = document.createElement("link"); cssLink.rel = "stylesheet"; cssLink.type = "text/css"; cssLink.href = url; var head = document.getElementsByTagName("head")[0]; head.appendChild(cssLink); } } 九十二、返回浏览器版本 function getExplorerInfo() { var explorer = window.navigator.userAgent.toLowerCase(); // ie if (explorer.indexOf("msie") >= 0) { var ver = explorer.match(/msie ([\d.]+)/)[1]; return { type: "IE", version: ver }; } // firefox else if (explorer.indexOf("firefox") >= 0) { var ver = explorer.match(/firefox\/([\d.]+)/)[1]; return { type: "Firefox", version: ver }; } // Chrome else if (explorer.indexOf("chrome") >= 0) { var ver = explorer.match(/chrome\/([\d.]+)/)[1]; return { type: "Chrome", version: ver }; } // Opera else if (explorer.indexOf("opera") >= 0) { var ver = explorer.match(/opera.([\d.]+)/)[1]; return { type: "Opera", version: ver }; } // Safari else if (explorer.indexOf("Safari") >= 0) { var ver = explorer.match(/version\/([\d.]+)/)[1]; return { type: "Safari", version: ver }; } } 九十三、是否为移动端 function isIos() { var u = navigator.userAgent; if (u.indexOf("Android") > -1 || u.indexOf("Linux") > -1) { //安卓手机 // return "Android"; return false; } else if (u.indexOf("iPhone") > -1) { //苹果手机 // return "iPhone"; return true; } else if (u.indexOf("iPad") > -1) { //iPad // return "iPad"; return false; } else if (u.indexOf("Windows Phone") > -1) { //winphone手机 // return "Windows Phone"; return false; } else { return false; } } 九十四、是否为PC端 function isPC() { var userAgentInfo = navigator.userAgent; var Agents = [ "Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod" ]; var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } 九十五、获取页面高度 function getPageHeight() { var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat" ? a : g.documentElement; return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight); } 九十六、 获取页面scrollLeft function getPageScrollLeft() { return document.documentElement.scrollLeft || document.body.scrollLeft; } 九十七、 获取页面宽度 getPageWidth: function () { var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat" ? a : g.documentElement; return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth); } 九十八、 获取页面scrollTop function getPageScrollTop() { return document.documentElement.scrollTop || document.body.scrollTop; } 九十九、 获取页面可视高度 function getPageViewHeight() { var d = document, a = d.compatMode == "BackCompat" ? d.body : d.documentElement; return a.clientHeight; } 一百、 拖动 拖拽 移动端拖动 // bindDrag(document.getElementById('b')); // touchDrag(document.getElementById('b')); function touchDrag(el) { var contW = $("#barrage").width(); var contH = $("#barrage").height(); var startX, startY, sX, sY, moveX, moveY, disX, disY; var winW = $(window).width(); var winH = $(window).height(); $(el).on({ //绑定事件 touchstart: function (e) { startX = e.originalEvent.targetTouches[0].pageX; //获取点击点的X坐标 startY = e.originalEvent.targetTouches[0].pageY; //获取点击点的Y坐标 sX = $(this).offset().left; //相对于当前窗口X轴的偏移量 sY = $(this).offset().top; //相对于当前窗口Y轴的偏移量 leftX = startX - sX; //鼠标所能移动的最左端是当前鼠标距div左边距的位置 rightX = winW - contW + leftX; //鼠标所能移动的最右端是当前窗口距离减去鼠标距div最右端位置 topY = startY - sY; //鼠标所能移动最上端是当前鼠标距div上边距的位置 bottomY = winH - contH + topY; //鼠标所能移动最下端是当前窗口距离减去鼠标距div最下端位置 }, touchmove: function (e) { e.preventDefault(); moveX = e.originalEvent.targetTouches[0].pageX; //移动过程中X轴的坐标 moveY = e.originalEvent.targetTouches[0].pageY; //移动过程中Y轴的坐标 if (moveX < leftX) { moveX = leftX; } if (moveX > rightX) { moveX = rightX; } if (moveY < topY) { moveY = topY; } if (moveY > bottomY) { moveY = bottomY; } $(this).css({ left: moveX + sX - startX, top: moveY + sY - startY }); } }); } pc端拖动 function bindDrag(el) { var _drag = {}; _drag.top = 0; //拖动过的位置距离上边 _drag.left = 0; //拖动过的位置距离左边 _drag.maxLeft; //距离左边最大的距离 _drag.maxTop; //距离上边最大的距离 _drag.dragging = false; //是否拖动标志 var winWidth = $(window).width(), winHeight = $(window).height(), objWidth = $(el).outerWidth(), objHeight = $(el).outerHeight(); (_drag.maxLeft = winWidth - objWidth), (_drag.maxTop = winHeight - objHeight); var els = el.style, x = 0, y = 0; var objTop = $(el).offset().top, objLeft = $(el).offset().left; $(el).mousedown(function (e) { _drag.dragging = true; _drag.isDragged = true; x = e.clientX - el.offsetLeft; y = e.clientY - el.offsetTop; el.setCapture && el.setCapture(); $(document) .bind("mousemove", mouseMove) .bind("mouseup", mouseUp); return false; }); function mouseMove(e) { e = e || window.event; if (_drag.dragging) { _drag.top = e.clientY - y; _drag.left = e.clientX - x; _drag.top = _drag.top > _drag.maxTop ? _drag.maxTop : _drag.top; _drag.left = _drag.left > _drag.maxLeft ? _drag.maxLeft : _drag.left; _drag.top = _drag.top < 0 ? 0 : _drag.top; _drag.left = _drag.left < 0 ? 0 : _drag.left; els.top = _drag.top + "px"; els.left = _drag.left + "px"; return false; } } function mouseUp(e) { _drag.dragging = false; el.releaseCapture && el.releaseCapture(); e.cancelBubble = true; $(document) .unbind("mousemove", mouseMove) .unbind("mouseup", mouseUp); } $(window).resize(function () { var winWidth = $(window).width(), winHeight = $(window).height(), el = $(el), elWidth = el.outerWidth(), elHeight = el.outerHeight(), elLeft = parseFloat(el.css("left")), elTop = parseFloat(el.css("top")); _drag.maxLeft = winWidth - elWidth; _drag.maxTop = winHeight - elHeight; _drag.top = _drag.maxTop < elTop ? _drag.maxTop : elTop; _drag.left = _drag.maxLeft < elLeft ? _drag.maxLeft : elLeft; el.css({ top: _drag.top, left: _drag.left }); }); } 101、阻止冒泡,点击其他地方元素消失 // 调用 preventBubble($("a"),$("#menu")); function preventBubble(tab, box) { tab.on("click", function (e) { box.show(); $(document).on("click", function () { box.hide(); }); e.stopPropagation(); }); box.on("click", function (e) { e.stopPropagation(); }); } 102、判断是否对象 function isObj(obj) { if (typeof obj == "object") { return true; } else { return false; } } 103、判断是否为空 function emptyFun(obj) { var obj = obj; if ( obj == "" || obj == null || obj == undefined || obj == "null" || obj == "undefined" ) { return true; } else { return false; } } 104、倒计时 function countDown(s) { var that = this; s--; $(".postverify").html(s + "秒后重发"); $("#time").text(s); var t = setTimeout(function () { that.countDown(s, t); }, 1000); if (s <= 0) { s = 60; clearTimeout(t); //把倒计时改成重新获取按钮 $(".postverify").text("重新发送"); } } 105、数组filter(搜索功能) // 数组filter(搜索功能)console.log(filterItems('ap',fruits)); // ['apple', 'grapes'] // var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; function filterItems(query, arr) { return arr.filter(function (el) { return el.toLowerCase().indexOf(query.toLowerCase()) > -1; }); } 106、时间戳转JS时间 function setTime(t) { function toDou(n) { return n < 10 ? "0" + n : "" + n; } var oDate = new Date(); oDate.setTime(t * 1000); return ( oDate.getFullYear() + "-" + (oDate.getMonth() + 1) + "-" + oDate.getDate() + " " + toDou(oDate.getHours()) + ":" + toDou(oDate.getMinutes()) + ":" + toDou(oDate.getSeconds()) ); } 107、标签切换 // 标签切换 //调用tabChange('#title-nav', '.option', '.productList', '.list'); function tabChange(btnBox, btn, tabBox, tab) { $(btnBox) .find(btn) .click(function () { var _this = $(this); _this.addClass("on") .siblings(btn) .removeClass("on"); var index = _this.index(); $(tab) .eq(index) .show() .siblings(tab) .hide(); }); } 108、生成从minNum到maxNum的随机数 function randomNum(minNum, maxNum) { return Math.floor(Math.random() * (maxNum - minNum + 1)) + min; } 109、url参数转对象 // @description url参数转对象 // @param {String} url default: window.location.href // @return {Object} function parseQueryString(url) { url = url == null ? window.location.href : url; var search = url[0] === "?" ? url.substr(1) : url.substring(url.lastIndexOf("?") + 1); if (search === "") return {}; search = search.split("&"); var query = {}; for (var i = 0; i < search.length; i++) { var pair = search[i].split("="); query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || ""); } return query; } 110、对象序列化(对象转成url参数) // @description 对象序列化(对象转成url参数) // @param {Object} obj // @return {String} function stringfyQueryString(obj) { if (!obj) return ""; var pairs = []; for (var key in obj) { var value = obj[key]; if (value instanceof Array) { for (var i = 0; i < value.length; ++i) { pairs.push( encodeURIComponent(key + "[" + i + "]") + "=" + encodeURIComponent(value[i]) ); } continue; } pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key])); } return pairs.join("&"); } 111、格式化现在距${endTime}的剩余时间 // @description 格式化现在距${endTime}的剩余时间 // @param {Date} endTime // @return {String} function formatRemainTime(endTime) { var startDate = new Date(); //开始时间 var endDate = new Date(endTime); //结束时间 var t = endDate.getTime() - startDate.getTime(); //时间差 var d = 0, h = 0, m = 0, s = 0; if (t >= 0) { d = Math.floor(t / 1000 / 3600 / 24); h = Math.floor((t / 1000 / 60 / 60) % 24); m = Math.floor((t / 1000 / 60) % 60); s = Math.floor((t / 1000) % 60); } return ( doubleNum(d) + "天 " + doubleNum(h) + "小时 " + doubleNum(m) + "分钟 " + doubleNum(s) + "秒" ); } 112、判断是否为URL地址 /** * @description 判断是否为URL地址 * @param {String} str * @return {Boolean} */ function isUrl(str) { return /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/i.test( str ); } 113、深度克隆对象或数组,多个对象或数组嵌套 function deepCopy(data) { const t = this.typeOf(data); var o; if (t === "array") { o = []; } else if (t === "object") { o = {}; } else { return data; } if (t === "array") { for (var i = 0; i < data.length; i++) { o.push(this.deepCopy(data[i])); } } else if (t === "object") { for (var i in data) { o[i] = this.deepCopy(data[i]); } } return o; } 114、生成随机字符串 len生成字符串长度,默认32位 function randomStr(len) { len = len || 32; var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; var maxPos = chars.length; var pwd = ""; for (var i = 0; i < len; i++) { pwd += chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } 115、保留n位小数 /* *保留n位小数 *@param num {Number|String} 原数字 1.33或者'1.33' *@returns {String} 返回字符串 */ function toThousands(num, n) { return parseFloat(num) .toFixed(n) .replace(/(\d{1,3})(?=(\d{3})+(?:\.))/g, "$1,"); } 116、时间转换秒数 /** * @param {s} 秒数 * @return {String} 字符串 * @example formatHMS(3610) // -> 1h0m10s */ function formatHMS(s) { var str = ""; if (s > 3600) { str = Math.floor(s / 3600) + "小时" + Math.floor((s % 3600) / 60) + "分钟" + (s % 60) + "秒"; } else if (s > 60) { str = Math.floor(s / 60) + "分钟" + (s % 60) + "秒"; } else { str = (s % 60) + "秒"; } return str; } 117、获取十六进制随机颜色 // /*获取十六进制随机颜色*/ $("#barrage").css("background",getRandomColor()); function getRandomColor() { return ( "#" + (function (h) { return new Array(7 - h.length).join("0") + h; })(((Math.random() * 0x1000000) << 0).toString(16)) ); } 118、获取字符串真实长度 汉字算两位 /** * 获取字符串真实长度 汉字算两位 * @param str * @returns {number} */ function getRealLength(str) { return isEmpty(str) ? 0 : str.replace(/[^\x00-\xff]/g, "**").length; } 119、排序 快速排序 function quickSort(arr) { //如果数组<=1,则直接返回 if (arr.length <= 1) { return arr; } var pivotIndex = Math.floor(arr.length / 2); //找基准,并把基准从原数组删除 var pivot = arr.splice(pivotIndex, 1)[0]; //定义左右数组 var left = []; var right = []; //比基准小的放在left,比基准大的放在right for (var i = 0; i < arr.length; i++) { if (arr[i] <= pivot) { left.push(arr[i]); } else { right.push(arr[i]); } } //递归 return quickSort(left).concat([pivot], quickSort(right)); } 冒泡排序 function bubbleSort(arr) { var len = arr.length; for (var i = 0; i < len; i++) { for (var j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // 相邻元素两两对比 var temp = arr[j + 1]; // 元素交换 arr[j + 1] = arr[j]; arr[j] = temp; } } } return arr; } 120、随机背景图 bgi(arar) function bgi(arr) { if (arr && arr.length > 0) { var index = Math.floor(Math.random() * arr.length); var img = arr[index]; function time() { document.body.style.backgroundImage = "url(" + img + ")"; } document.body.onload = function () { time(); }; } } 121、获取浏览器版本 function getBrowserVersion() { var result; var Sys = {}; var ua = navigator.userAgent.toLowerCase(); var s; (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? (Sys.ie = s[1]) : (s = ua.match(/msie ([\d.]+)/)) ? (Sys.ie = s[1]) : (s = ua.match(/firefox\/([\d.]+)/)) ? (Sys.firefox = s[1]) : (s = ua.match(/chrome\/([\d.]+)/)) ? (Sys.chrome = s[1]) : (s = ua.match(/opera.([\d.]+)/)) ? (Sys.opera = s[1]) : (s = ua.match(/version\/([\d.]+).*safari/)) ? (Sys.safari = s[1]) : 0; if (Sys.ie) result = "IE: " + Sys.ie; if (Sys.firefox) result = "Firefox: " + Sys.firefox; if (Sys.chrome) result = "Chrome: " + Sys.chrome; if (Sys.opera) result = "Opera: " + Sys.opera; if (Sys.safari) result = "Safari: " + Sys.safari; return result; } 122、判断Javascript执行环境 function ele() { if (typeof window === "undefined") { console.log("node"); } else { console.log("browser"); } } 123、判断手机设备 // 判断手机设备是ios系统,还是安卓(android)系统,或者是iphone。 // getMobileSystem() 返回“1”是安卓手机;返回“2||3”是ios系统;返回“3”是iphoneX;返回“0”是其他系统。 function getMobileSystem() { var u = navigator.userAgent; var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android系统 var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios系统 var iphoneX = /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375); // 返回1是android系统 if (isAndroid) { return 1; } // 返回2是ios系统 if (isiOS && !iphoneX) { return 2; } // 返回3是iphoneX if (iphoneX) { return 3; } return 0; } 124、获取时间 2018年12月26日 15:05:16 星期三 function showTime() { var week = new Array( "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" ); var now = new Date(); var year = now.getFullYear(); var month = now.getMonth(); var date = now.getDate(); var day = now.getDay(); var hour = now.getHours(); var minutes = now.getMinutes(); var second = now.getSeconds(); month < 10 ? (month = "0" + month) : month; month = month + 1; hour < 10 ? (hour = "0" + hour) : hour; minutes < 10 ? (minutes = "0" + minutes) : minutes; second < 10 ? (second = "0" + second) : second; var now_time = year + "年" + month + "月" + date + "日" + " " + hour + ":" + minutes + ":" + "" + second + " " + week[day - 1]; document.getElementById("showtime").innerHTML = now_time; setTimeout("showTime();", 1000); //每隔1秒刷新一次 } 125、去掉url前缀 function removeUrlPrefix(a){ a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/"); while(trim(a).toLowerCase().indexOf("http://")==0){ a=trim(a.replace(/http:\/\//i,"")); } return a; } 126、随机数时间戳 function uniqueId(){ var a=Math.random,b=parseInt; return Number(new Date()).toString()+b(10*a())+b(10*a())+b(10*a()); } 127、时间个性化输出功能 /* 1、< 60s, 显示为“刚刚” 2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前” 3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX” 4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX” 5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX” */ function timeFormat(time){ var date = new Date(time), curDate = new Date(), year = date.getFullYear(), month = date.getMonth() + 10, day = date.getDate(), hour = date.getHours(), minute = date.getMinutes(), curYear = curDate.getFullYear(), curHour = curDate.getHours(), timeStr; if(year < curYear){ timeStr = year +'年'+ month +'月'+ day +'日 '+ hour +':'+ minute; }else{ var pastTime = curDate - date, pastH = pastTime/3600000; if(pastH > curHour){ timeStr = month +'月'+ day +'日 '+ hour +':'+ minute; }else if(pastH >= 1){ timeStr = '今天 ' + hour +':'+ minute +'分'; }else{ var pastM = curDate.getMinutes() - minute; if(pastM > 1){ timeStr = pastM +'分钟前'; }else{ timeStr = '刚刚'; } } } return timeStr; } 128、数学函数 // Math对象 1. Math.abs(num) //返回num的绝对值 2. Math.acos(num) //返回num的反余弦值 3. Math.asin(num) //返回num的反正弦值 4. Math.atan(num) // 返回num的反正切值 5. Math.atan2(y,x) //返回y除以x的商的反正切值 6. Math.ceil(num) // 返回大于num的最小整数 7. Math.cos(num) // 返回num的余弦值 8. Math.exp(x) // 返回以自然数为底,x次幂的数 9. Math.floor(num) // 返回小于num的最大整数 10.Math.log(num) // 返回num的自然对数 11.Math.max(num1,num2) // 返回num1和num2中较大的一个 12.Math.min(num1,num2) // 返回num1和num2中较小的一个 13.Math.pow(x,y) // 返回x的y次方的值 14.Math.random() // 返回0到1之间的一个随机数 15.Math.round(num) // 返回num四舍五入后的值 16.Math.sin(num) // 返回num的正弦值 17.Math.sqrt(num) // 返回num的平方根 18.Math.tan(num) // 返回num的正切值 19.Math.E // 自然数(2.718281828459045) 20.Math.LN2 // 2的自然对数(0.6931471805599453) 21.Math.LN10 // 10的自然对数(2.302585092994046) 22.Math.LOG2E // log 2 为底的自然数(1.4426950408889634) 23.Math.LOG10E // log 10 为底的自然数(0.4342944819032518) 24.Math.PI // π(3.141592653589793) 25.Math.SQRT1_2 // 1/2的平方根(0.7071067811865476) 26.Math.SQRT2 // 2的平方根(1.4142135623730951) 129、返回刷新 function CheckReload() { if (window.name != bencalie) { location.reload(); window.name = bencalie; } else { window.name = ''; } } 130、让指定的DIV始终显示在屏幕正中间 function letDivCenter(divName) { var top = ($(window).height() - $(divName).height()) / 2; var left = ($(window).width() - $(divName).width()) / 2; var scrollTop = $(document).scrollTop(); var scrollLeft = $(document).scrollLeft(); $(divName).css({ position: 'absolute', 'top': top + scrollTop, left: left + scrollLeft }).show(); } 131、判断是手机还是电脑访问 //flag返回值为true则说明是电脑客户端 function check() { var userAgentInfo = navigator.userAgent; var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod", "BlackBerry", "webOS"); var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } 132、页面禁止查看源代码函数 //阻止右键,F12查看源码 function re() { document.onkeydown = function () { var e = window.event || arguments[0]; if (e.keyCode == 123) { alert('请尊重劳动成果!'); return false; } else if ((e.ctrlKey) && (e.shiftKey) && (e.keyCode == 73)) { alert('请尊重劳动成果!'); return false; } else if ((e.ctrlKey) && (e.keyCode == 85)) { alert('请尊重劳动成果!'); return false; } else if ((e.ctrlKey) && (e.keyCode == 83)) { alert('请尊重劳动成果!'); return false; } } document.oncontextmenu = function () { alert('请尊重劳动成果!'); return false; } } 133、enter键快速登录或搜索 document.onkeydown = function (event) { var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && e.keyCode == 13) { // Login(); } } 134、字符串循环复制 //repeatStr(str->字符串, count->次数) //repeatStr('123',3) //"result:123123123" function repeatStr(str, count) { var text = ''; for (var i = 0; i < count; i++) { text += str; } return text; } 135、字符串替换 //replaceAll('这里是上海,中国第三大城市,广东省省会,简称穗,','上海','广州') //result:"这里是广州,中国第三大城市,广东省省会,简称穗," function replaceAll(str, AFindText, ARepText) { raRegExp = new RegExp(AFindText, "g"); return str.replace(raRegExp, ARepText); } 136、检测字符串 //检测字符串 //checkType('165226226326','phone') //result:false //大家可以根据需要扩展 function checkType(str, type) { switch (type) { case 'email': return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case 'phone': return /^1[3|4|5|7|8][0-9]{9}$/.test(str); case 'tel': return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); case 'number': return /^[0-9]$/.test(str); case 'english': return /^[a-zA-Z]+$/.test(str); case 'text': return /^\w+$/.test(str); case 'chinese': return /^[\u4E00-\u9FA5]+$/.test(str); case 'lower': return /^[a-z]+$/.test(str); case 'upper': return /^[A-Z]+$/.test(str); default: return true; } } 137、从数组中随机获取元素 //randomOne([1,2,3,6,8,5,4,2,6]) //2 //randomOne([1,2,3,6,8,5,4,2,6]) //8 //randomOne([1,2,3,6,8,5,4,2,6]) //8 //randomOne([1,2,3,6,8,5,4,2,6]) //1 function randomOne(arr) { return arr[Math.floor(Math.random() * arr.length)]; } 138、原生js检测对象是否有哪个类名 // console.log(hasClass(document.getElementById("aaa"),"cur")) --> true function hasClass(obj, classStr) { if (obj.className && $.trim(obj.className) !== "") { var arr = obj.className.split(/\s+/); //这个正则表达式是因为class可以有多个,判断是否包含 return (arr.indexOf(classStr) == -1) ? false : true; } else { return false; } } 139、JS提取身份证中的性别和出生日期信息 //身份证号 倒数第二位是性别,奇数为男,偶数为女 function getIdcardData(){ var ido=document.getElementById('idCardNumberHandle');//身份证号input元素的ID var bd=document.getElementById('birthdayHandle'); var sex=document.getElementById('sexHandle'); if(!/^\d{6}((?:19|20)((?:\d{2}(?:0[13578]|1[02])(?:0[1-9]|[12]\d|3[01]))|(?:\d{2}(?:0[13456789]|1[012])(?:0[1-9]|[12]\d|30))|(?:\d{2}02(?:0[1-9]|1\d|2[0-8]))|(?:(?:0[48]|[2468][048]|[13579][26])0229)))\d{2}(\d)[xX\d]$/.test(ido.value)){ alert('身份证号非法.'); return; } bd.value=(RegExp.$1).substr(0,4)+'-'+(RegExp.$1).substr(4,2)+'-'+(RegExp.$1).substr(6,2);//设置出生日期 ex.value=(parseInt(ido.value.charAt(ido.value.length-2))%2==0?'女':'男');//设置性别 } 140、类型判断 function isString(o) { //是否字符串 return Object.prototype.toString.call(o).slice(8, -1) === 'String' } function isNumber(o) { //是否数字 return Object.prototype.toString.call(o).slice(8, -1) === 'Number' } function isBoolean(o) { //是否boolean return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean' } function isFunction(o) { //是否函数 return Object.prototype.toString.call(o).slice(8, -1) === 'Function' } function isNull(o) { //是否为null return Object.prototype.toString.call(o).slice(8, -1) === 'Null' } function isUndefined(o) { //是否undefined return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined' } function isObj(o) { //是否对象 return Object.prototype.toString.call(o).slice(8, -1) === 'Object' } function isArray(o) { //是否数组 return Object.prototype.toString.call(o).slice(8, -1) === 'Array' } function isDate(o) { //是否时间 return Object.prototype.toString.call(o).slice(8, -1) === 'Date' } function isRegExp(o) { //是否正则 return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp' } function isError(o) { //是否错误对象 return Object.prototype.toString.call(o).slice(8, -1) === 'Error' } function isSymbol(o) { //是否Symbol函数 return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol' } function isPromfunctionise(o) { //是否Promfunction ise对象 return Object.prototype.toString.call(o).slice(8, -1) === 'Promfunction ise' } function isSet(o) { //是否Set对象 return Object.prototype.toString.call(o).slice(8, -1) === 'Set' } function isFalse(o) { if (!o || o === 'null' || o === 'undefined' || o === 'false' || o === 'NaN') return true return false } function checkStr(str, type) { switch (type) { case "phone": //手机号码 return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str); case "tel": //座机 return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); case "card": //身份证 return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); case "pwd": //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线 return /^[a-zA-Z]\w{5,17}$/.test(str); case "postal": //邮政编码 return /[1-9]\d{5}(?!\d)/.test(str); case "QQ": //QQ号 return /^[1-9][0-9]{4,9}$/.test(str); case "email": //邮箱 return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case "money": //金额(小数点2位) return /^\d*(?:\.\d{0,2})?$/.test(str); case "URL": //网址 return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test( str ); case "IP": //IP return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test( str ); case "date": //日期时间 return ( /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test( str ) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str) ); case "number": //数字 return /^[0-9]$/.test(str); case "english": //英文 return /^[a-zA-Z]+$/.test(str); case "chinese": //中文 return /^[\u4E00-\u9FA5]+$/.test(str); case "lower": //小写 return /^[a-z]+$/.test(str); case "upper": //大写 return /^[A-Z]+$/.test(str); case "HTML": //HTML标记 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); default: return true; } } 141、js点击缩略图显示大图 html结构
js $(function () { $(".pimg").click(function () { var _this = $(this); //将当前的pimg元素作为_this传入函数 imgShow("#outerdiv", "#innerdiv", "#bigimg", _this); }); }); function imgShow(outerdiv, innerdiv, bigimg, _this) { var src = _this.attr("src"); //获取当前点击的pimg元素中的src属性 $(bigimg).attr("src", src); //设置#bigimg元素的src属性 /*获取当前点击图片的真实大小,并显示弹出层及大图*/ $("").attr("src", src).load(function () { var windowW = $(window).width(); //获取当前窗口宽度 var windowH = $(window).height(); //获取当前窗口高度 var realWidth = this.width; //获取图片真实宽度 var realHeight = this.height; //获取图片真实高度 var imgWidth, imgHeight; var scale = 0.8; //缩放尺寸,当图片真实宽度和高度大于窗口宽度和高度时进行缩放 if (realHeight > windowH * scale) { //判断图片高度 imgHeight = windowH * scale; //如大于窗口高度,图片高度进行缩放 imgWidth = imgHeight / realHeight * realWidth; //等比例缩放宽度 if (imgWidth > windowW * scale) { //如宽度扔大于窗口宽度 imgWidth = windowW * scale; //再对宽度进行缩放 } } else if (realWidth > windowW * scale) { //如图片高度合适,判断图片宽度 imgWidth = windowW * scale; //如大于窗口宽度,图片宽度进行缩放 imgHeight = imgWidth / realWidth * realHeight; //等比例缩放高度 } else { //如果图片真实高度和宽度都符合要求,高宽不变 imgWidth = realWidth; imgHeight = realHeight; } $(bigimg).css("width", imgWidth); //以最终的宽度对图片缩放 var w = (windowW - imgWidth) / 2; //计算图片与窗口左边距 var h = (windowH - imgHeight) / 2; //计算图片与窗口上边距 $(innerdiv).css({ "top": h, "left": w }); //设置#innerdiv的top和left属性 $(outerdiv).fadeIn("fast"); //淡入显示#outerdiv及.pimg }); $(outerdiv).click(function () { //再次点击淡出消失弹出层 $(this).fadeOut("fast"); }); }