分享前端開發常用代碼片段
作者:WEBING
segmentfault.com/a/1190000014700549
一、預載入圖像
如果你的網頁中需要使用大量初始不可見的(例如,懸停的)圖像,那麼可以預載入這些圖像。
二、檢查圖像是否載入
有時為了繼續腳本,你可能需要檢查圖像是否全部載入完畢。
你也可以使用 ID 或 CLASS 替換 標籤來檢查某個特定的圖像是否被載入。
三、自動修復破壞的圖像
逐個替換已經破壞的圖像鏈接是非常痛苦的。不過,下面這段簡單的代碼可以幫助你。
四、懸停切換
當用戶滑鼠懸停在可點擊的元素上時,可添加類到元素中,反之則移除類。
只需要添加必要的 CSS 即可。更簡單的方法是使用 toggleClass() 方法。
五、淡入淡出/顯示隱藏
六、滑鼠滾輪
$("#content").on("mousewheel DOMMouseScroll",function(event){
// chrome & ie || // firefox
vardelta=(event.originalEvent.wheelDelta&&(event.originalEvent.wheelDelta>?1: -1))||
(event.originalEvent.detail&&(event.originalEvent.detail>?-1:1));
if(delta>){
console.log("mousewheel top");
}elseif(delta
console.log("mousewheel bottom");
}
});
七、滑鼠坐標
1、JavaScript實現
X: Y:
functionmousePosition(ev){
if(ev.pageX||ev.pageY){
return{x:ev.pageX,y:ev.pageY};
}
return{
};
}
functionmouseMove(ev){
ev=ev||window.event;
varmousePos=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+" Y:"+event.offsetY);
//獲取元素相對於頁面的坐標
console.log("X:"+$(this).offset().left+" 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
functionisSupportSVG(){
varSVG_NS="http://www.w3.org/2000/svg";
return!!document.createElementNS&&!!document.createElementNS(SVG_NS,"svg").createSVGRect;
}
console.log(isSupportSVG());
十二、檢測瀏覽器是否支持canvas
functionisSupportCanvas(){
if(document.createElement("canvas").getContext){
returntrue;
}else{
returnfalse;
}
}
console.log(isSupportCanvas());
十三、檢測是否是微信瀏覽器
varua=navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger"){
returntrue;
}else{
returnfalse;
}
}
十四、檢測是否移動端及瀏覽器內核
varbrowser={
versions:function(){
varu=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.+MacOSX/),//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("移動端");
}
十五、檢測是否電腦端/移動端
varbrowser={
versions:function(){
varu=navigator.userAgent,app=navigator.appVersion;
varsUserAgent=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.+MacOSX/),
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
};
}()
}
window.location="http:/www.baidu.com/m/";
}
十六、檢測瀏覽器內核
functiongetInternet(){
if(navigator.userAgent.indexOf("MSIE")>){
return"MSIE";//IE瀏覽器
}
if(isFirefox=navigator.userAgent.indexOf("Firefox")>){
return"Firefox";//Firefox瀏覽器
}
if(isSafari=navigator.userAgent.indexOf("Safari")>){
return"Safari";//Safan瀏覽器
}
if(isCamino=navigator.userAgent.indexOf("Camino")>){
return"Camino";//Camino瀏覽器
}
if(isMozilla=navigator.userAgent.indexOf("Gecko/")>){
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();
十八、電腦端頁面全屏顯示
functionfullscreen(element){
if(element.requestFullscreen){
element.requestFullscreen();
}elseif(element.mozRequestFullScreen){
element.mozRequestFullScreen();
}elseif(element.webkitRequestFullscreen){
element.webkitRequestFullscreen();
}elseif(element.msRequestFullscreen){
element.msRequestFullscreen();
}
}
fullscreen(document.documentElement);
十九、獲得/失去焦點
1、JavaScript實現
// JavaScript
window.onload=function(){
varoIpt=document.getElementById("i_input");
if(oIpt.value=="會員卡號/手機號"){
}else{
};
oIpt.onfocus=function(){
if(this.value=="會員卡號/手機號"){
this.value="";
this.type="password";
}else{
}
};
oIpt.onblur=function(){
if(this.value==""){
this.value="會員卡號/手機號";
this.type="text";
}
};
}
2、jQuery實現
// jQuery
$("#showPwd").focus(function(){
vartext_value=$(this).val();
if(text_value=="請輸入您的註冊密碼"){
$("#showPwd").hide();
$("#password").show().focus();
}
});
$("#password").blur(function(){
vartext_value=$(this).val();
if(text_value==""){
$("#showPwd").show();
$("#password").hide();
}
});
二十、獲取上傳文件大小
// 兼容IE9低版本
functiongetFileSize(obj){
varfilesize;
if(obj.files){
filesize=obj.files[].size;
}else{
try{
varpath,fso;
path=document.getElementById("filePath").value;
fso=newActiveXObject("Scripting.FileSystemObject");
filesize=fso.GetFile(path).size;
}
catch(e){
// 在IE9及低版本瀏覽器,如果不容許ActiveX控制項與頁面交互,點擊了否,就無法獲取size
console.log(e.message);// Automation 伺服器不能創建對象
filesize="error";// 無法獲取
}
}
returnfilesize;
}
二十一、限制上傳文件類型
1、高版本瀏覽器
2、限制圖片
3、低版本瀏覽器
/* 通過擴展名,檢驗文件格式。
* @parma filePath 文件路徑
* @parma acceptFormat 允許的文件類型
* @result 返回值:true or false
*/
functioncheckFormat(filePath,acceptFormat){
varresultBool=false,
ex=filePath.substring(filePath.lastIndexOf(".")+1);
ex=ex.toLowerCase();
for(vari=;i
if(acceptFormat[i]==ex){
resultBool=true;
break;
}
}
returnresultBool;
};
functionlimitTypes(){
varobj=document.getElementById("filePath");
varpath=obj.value;
varresult=checkFormat(path,["bmp","jpg","jpeg","png"]);
if(!result){
alert("上傳類型錯誤,請重新上傳");
obj.value="";
}
}
二十二、正則表達式
//驗證郵箱
/^w+@([-9a-zA-Z]+[.])+[a-z]{2,4}$/
//驗證手機號
/^1[3|5|8|7]d{9}$/
//驗證URL
/^http://.+./
//驗證身份證號碼
/(^d{15}$)|(^d{17}([-9]|X|x)$)/
//匹配字母、數字、中文字元
/^([A-Za-z0-9]|[u4e00-u9fa5])*$/
//匹配中文字元
/[u4e00-u9fa5]/
//匹配雙位元組字元(包括漢字)
/[^x00-xff]/
二十三、限制字元數
//字元串截取
functiongetByteVal(val,max){
varreturnValue="";
varbyteValLen=;
for(vari=;imax)break;
returnValue+=val[i];
}
returnreturnValue;
}
$("#txt").on("keyup",function(){
varval=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
send.value = "發送驗證碼";
clearInterval(timer);
send.disabled = false;
times = 60;
} else {
send.value = times + "秒後重試";
send.disabled = true;
}
}, 1000);
}
vartimes=60,
timer=null;
$("#send").on("click",function(){
var$this=$(this);
// 計時開始
timer=setInterval(function(){
times--;
if(times
$this.val("發送驗證碼");
clearInterval(timer);
$this.attr("disabled",false);
times=60;
}else{
$this.val(times+"秒後重試");
$this.attr("disabled",true);
}
},1000);
});
二十五、時間倒計時
vartimes=60,
timer=null;
$("#send").on("click",function(){
var$this=$(this);
// 計時開始
timer=setInterval(function(){
times--;
if(times
$this.val("發送驗證碼");
clearInterval(timer);
$this.attr("disabled",false);
times=60;
}else{
$this.val(times+"秒後重試");
$this.attr("disabled",true);
}
},1000);
});
二十六、倒計時跳轉
// 設置倒計時秒數
vart=10;
// 顯示倒計時秒數
functionshowTime(){
t-=1;
document.getElementById("showtimes").innerHTML=t;
if(t==){
location.href="error404.asp";
}
//每秒執行一次 showTime()
setTimeout("showTime()",1000);
}
showTime();
二十七、時間戳、毫秒格式化
functionformatDate(now){
vary=now.getFullYear();
varm=now.getMonth()+1;// 注意 JavaScript 月份+1
vard=now.getDate();
varh=now.getHours();
varm=now.getMinutes();
vars=now.getSeconds();
returny+"-"+m+"-"+d+" "+h+":"+m+":"+s;
}
alert(formatDate(nowDate));
二十八、當前日期
varcalculateDate=function(){
vardate=newDate();
varweeks=["日","一","二","三","四","五","六"];
returndate.getFullYear()+"年"+(date.getMonth()+1)+"月"+
date.getDate()+"日 星期"+weeks[date.getDay()];
}
$(function(){
$("#dateSpan").html(calculateDate());
});
二十九、判斷周六/周日
functiontime(y,m){
vartempTime=newDate(y,m,);
vartime=newDate();
varsaturday=newArray();
varsunday=newArray();
for(vari=1;i
time.setFullYear(y,m-1,i);
varday=time.getDay();
if(day==6){
saturday.push(i);
}elseif(day==){
sunday.push(i);
}
}
vartext=y+"年"+m+"月份"+"
"
+"周六:"+saturday.toString()+"
"
+"周日:"+sunday.toString();
document.getElementById("text").innerHTML=text;
}
time(2018,5);
三十、AJAX調用錯誤處理
當 Ajax 調用返回 404 或 500 錯誤時,就執行錯誤處理程序。如果沒有定義處理程序,其他的 jQuery 代碼或會就此罷工。定義一個全局的 Ajax 錯誤處理程序
三十一、鏈式插件調用
jQuery 允許「鏈式」插件的方法調用,以減輕反覆查詢 DOM 並創建多個 jQuery 對象的過程。
通過使用鏈式,可以改善
還有一種方法是在(前綴$)變數中高速緩存元素
鏈式和高速緩存的方法都是 jQuery 中可以讓代碼變得更短和更快的最佳做法。
本文在GitHub的地址 Common-code


TAG:前端開發 |