分享前端開發常用程式碼片段-值得收藏
阿新 • • 發佈:2018-11-27
一、預載入影象
如果你的網頁中需要使用大量初始不可見的(例如,懸停的)影象,那麼可以預載入這些影象。
二、檢查影象是否載入
有時為了繼續指令碼,你可能需要檢查影象是否全部載入完畢。
你也可以使用 ID 或 CLASS 替換 <img>標籤來檢查某個特定的影象是否被載入。
三、自動修復破壞的影象
逐個替換已經破壞的影象連結是非常痛苦的。不過,下面這段簡單的程式碼可以幫助你。
四、懸停切換
當用戶滑鼠懸停在可點選的元素上時,可新增類到元素中,反之則移除類。
只需要新增必要的 CSS 即可。更簡單的方法是使用 toggleClass() 方法。
五、淡入淡出/顯示隱藏
六、滑鼠滾輪
$('#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:<input id="xxx" type="text" /> Y:<input id="yyy" type="text" />
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實現
<body ontouchmove="event.preventDefault()" >
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實現
<input id="i_input" type="text" value='會員卡號/手機號'/><
// 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="text" class="oldpsw" id="showPwd" value="請輸入您的註冊密碼"/>
<input type="password" name="psw" class="oldpsw" id="password" value="" style="display:none;"/></pre>
<pre style="margin: 8px 0px; padding: 8px; font-family: Arial; border: 1px solid rgb(204, 204, 204); background: rgb(243, 243, 243); color: rgb(85, 85, 85); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 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();
}
});
二十、獲取上傳檔案大小
<input type="file" id="filePath" onchange="getFileSize(this)"/></pre>
<pre style="margin: 8px 0px; padding: 8px; font-family: Arial; border: 1px solid rgb(204, 204, 204); background: rgb(243, 243, 243); color: rgb(85, 85, 85); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 相容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、高版本瀏覽器
<input type="file" name="filePath" accept=".jpg,.jpeg,.doc,.docxs,.pdf">
2、限制圖片
<input type="file" class="file" value="上傳" accept="image/*"/>
3、低版本瀏覽器
<input type="file" id="filePath" onchange="limitTypes()"/>
/* 通過副檔名,檢驗檔案格式。
* @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 = '';
}
}
二十二、正則表示式
//驗證郵箱
/^\[email protected]([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]/
二十三、限制字元數
<input id="txt" type="text">
//字串擷取
function getByteVal(val, max) {
var returnValue = '';
var byteValLen = 0;
for (var i = 0; i < val.length; i++) { if (val[i].match(/[^\x00-\xff]/ig) != 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);
}
});
二十四、驗證碼倒計時
<input id="send" type="button" value="傳送驗證碼">
// 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);
});
二十五、時間倒計時
<p id="_lefttime"></p>
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);
二十六、倒計時跳轉
<div id="showtimes"></div>
// 設定倒計時秒數
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());
});
二十九、判斷週六/週日
<p id="text"></p>
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+"月份"+"<br />"
+"週六:"+saturday.toString()+"<br />"
+"週日:"+sunday.toString();
document.getElementById("text").innerHTML = text;
}
time(2018,5);
三十、AJAX呼叫錯誤處理
當 Ajax 呼叫返回 404 或 500 錯誤時,就執行錯誤處理程式。如果沒有定義處理程式,其他的 jQuery 程式碼或會就此罷工。定義一個全域性的 Ajax 錯誤處理程式
三十一、鏈式外掛呼叫
jQuery 允許“鏈式”外掛的方法呼叫,以減輕反覆查詢 DOM 並建立多個 jQuery 物件的過程。
通過使用鏈式,可以改善
還有一種方法是在(字首$)變數中快取記憶體元素
鏈式和快取記憶體的方法都是 jQuery 中可以讓程式碼變得更短和更快的最佳做法。
本次給大家推薦一個免費的學習群,裡面概括移動應用網站開發,css,html,webpack,vue node angular以及面試資源等。
對web開發技術感興趣的同學,歡迎加入Q群:943129070,不管你是小白還是大牛我都歡迎,還有大牛整理的一套高效率學習路線和教程與您免費分享,同時每天更新視訊資料。
最後,祝大家早日學有所成,拿到滿意offer,快速升職加薪,走上人生巔峰。