刚开发完一个移动端的项目,博主总结了一些其中常用到的方法和功能,欢迎大家来拍砖和完善。
1.浏览器HTML5内核检测网址
http://chrome.360.cn/test/html5/index.html
2.移动端字体计算
var fontSize = 16; //基准字体大小 var elm = document.documentElement; elm.style.fontSize = fontSize * (elm.clientWidth/320) + 'px'; if(elm.clientWidth >= 768 ){ elm.style.fontSize = fontSize *2.4 + 'px';
3.判断是否为微信内置浏览器
function is_weixin(){
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger" || ua.indexOf("QQBrowser")>=0 || ua.indexOf("QQ")>=0) {
(".alipay").css('display','none');
} else {(".alipay").css('display','block');
return false;
}
}
4.mdpi
mdpi区间的手机,dp=px。 hdpi区间的手机,1dp=1.5px。 xhdpi区间的手机,1dp=2px。 xxhdpi区间的手机,1dp=3px。 在3GS上,1point=1px。 在iPhone4上,1point=2px。 在iPhone5上,1point=2px。 在iPhone6上,1point=2px。 在iPhone6 plus上,1point=3px。
5.form表单post提交禁止URL地址栏数据
$("#form1").submit(function(event){ event.preventDefault(); ...... } //禁止链接跳转
6.获取地址栏某参数值
方法一: function getUrlParam(key) { var url = window.location.search; var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); var result = url.substr(1).match(reg); return result ? decodeURIComponent(result[2]) : null; } console.log(getUrlParam('title')); 方法二:获取http://www.baidu.com/lists/1/4/3中的数字‘1’ var a = window.location.href.split("/lists/")[1].split("/")[0]; console.log(a); 方法三:获取URL中的数字‘12345’ var url = "http://www.baidu.com/api.php/mproducts/lists/12345/2"; // location.href var result = location.href.match(/mproducts\/lists\/(\d+)\/(\d+)/i); console.log( result[1] ); 方法四: function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); } } return theRequest; } var Request = new Object(); Request = GetRequest(); console.log(Request['id']); console.log(Request['reason']);
7.判断浏览器的类型:
function browserRedirect() { var c = navigator.userAgent.toLowerCase(); var g = c.match(/ipad/i) == "ipad"; var h = c.match(/iphone os/i) == "iphone os"; var f = c.match(/midp/i) == "midp"; var d = c.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; var e = c.match(/ucweb/i) == "ucweb"; var a = c.match(/android/i) == "android"; var b = c.match(/windows ce/i) == "windows ce"; var i = c.match(/windows mobile/i) == "windows mobile"; if (g || h || f || d || e || a || b || i) { alert("PC端"); } else { alert("移动端"); } } browserRedirect();
8.城市定位:
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=C93b5178d7a8ebdb830b9b557abce78b"></script> var localCity = new BMap.LocalCity(); localCity.get(function (r) { console.log(r.name); }); });
9.移动端长按提醒
.fn.longPress = function(fn) { var timeout = undefined; varthis = this; for(var i = 0;i<this.length;i++){this[i].addEventListener('touchstart', function(event) { timeout = setTimeout(fn, 800); //长按时间超过800ms,则执行传入的方法 }, false); this[i].addEventListener('touchend', function(event) { clearTimeout(timeout); //长按时间少于800ms,不会执行传入的方法 }, false); } }('.object').longPress(function(){ alert("删除"); });
10.捕捉用户点击浏览器或手机返回键跳转到指定页面,修改history.APi
if (window.history && window.history.pushState) { $(window).on('popstate', function() { var hashLocation = location.hash; var hashSplit = hashLocation.split("#!/"); var hashName = hashSplit[1]; if (hashName !== '') { var hash = window.location.hash; if (hash === '') { window.location.href='http://www.1yhhw.com/index.php/member'; } } }); window.history.pushState('forward', null, './#forward'); }
11.N秒倒计时后跳转(一般常见于404页面)
var i = 4; function getTime() { document.getElementById('time').innerHTML = "<font color='#ff9e19'>" + i + "</font>"; i -= 1; var x = setTimeout('getTime()', 1000) if (i <= 0) { clearTimeout(x); } if(i==1){ window.location.href='/'; } } window.onload = getTime;
12.javascript时间戳和日期字符串相互转换
获取当前时间撮:
方法一:var timestamp = (new Date()).valueOf(); 方法二:var timestamp=new Date().getTime(); 方法三:var timestamp = Date.parse(new Date()); // 把毫秒改成000显示 //时间戳转换成日期时间2014-8-8 下午11:40:20 function formatDate(ns){ return new Date(parseInt(ns) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); } //时间戳转换成八位日期2014-5-5 function userDate(uData){ var myDate = new Date(uData*1000); var year = myDate.getFullYear(); var month = myDate.getMonth() + 1; var day = myDate.getDate(); return year + '-' + month + '-' + day; } //时间戳转换成四位时间10:10 function userTime(uTime){ var myDate = new Date(uTime*1000); var hours = myDate.getHours(); var minutes = myDate.getMinutes(); return hours + ':' + minutes; } //时间戳转换成四位时间10:10:00 function userTime(uTime){ var myDate = new Date(uTime*1000); var hours = myDate.getHours(); var minutes = myDate.getMinutes(); var second = myDate.getSeconds(); return hours + ':' + minutes + ':' + second; } //定时提醒设置的时间传入 (2014,05,15)返回成2014-01-21 function setDate(year,month,day){ return year + '-' + month + '-' + day; } //定时提醒设置的时间传入 (01:02)返回成01:01:00 function setTime(hour,minute){ return hour + ':' + minute+ ':00'; } //时间格式2014-02-02 14:10:00改成时间戳 function js_strto_time(str_time){ var new_str = str_time.replace(/:/g,"-"); new_str = new_str.replace(/ /g,"-"); var arr = new_str.split("-"); var datum = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5])); return strtotime = datum.getTime()/1000; } //时间戳改成时间格式2014-12-12 下午01:10 function js_date_time(unixtime){ var timestr = new Date(parseInt(unixtime) * 1000); var datetime = timestr.toLocaleString().replace(/年|月/g,"-").replace(/日/g," "); return datetime; } // 获取当前时间戳(以s为单位) var timestamp = Date.parse(new Date()); timestamp = timestamp / 1000; //当前时间戳为:1403149534 console.log("当前时间戳为:" + timestamp); // 获取某个时间格式的时间戳 var stringTime = "2014-07-10 10:21:12"; var timestamp2 = Date.parse(new Date(stringTime)); timestamp2 = timestamp2 / 1000; //2014-07-10 10:21:12的时间戳为:1404958872 console.log(stringTime + "的时间戳为:" + timestamp2); // 将当前时间换成时间格式字符串 var timestamp3 = 1403058804; var newDate = new Date(); newDate.setTime(timestamp3 * 1000); // Wed Jun 18 2014 console.log(newDate.toDateString()); // Wed, 18 Jun 2014 02:33:24 GMT console.log(newDate.toGMTString()); // 2014-06-18T02:33:24.000Z console.log(newDate.toISOString()); // 2014-06-18T02:33:24.000Z console.log(newDate.toJSON()); // 2014年6月18日 console.log(newDate.toLocaleDateString()); // 2014年6月18日 上午10:33:24 console.log(newDate.toLocaleString()); // 上午10:33:24 console.log(newDate.toLocaleTimeString()); // Wed Jun 18 2014 10:33:24 GMT+0800 (中国标准时间) console.log(newDate.toString()); // 10:33:24 GMT+0800 (中国标准时间) console.log(newDate.toTimeString()); // Wed, 18 Jun 2014 02:33:24 GMT console.log(newDate.toUTCString()); Date.prototype.format = function(format) { var date = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S+": this.getMilliseconds() }; if (/(y+)/i.test(format)) { format = format.replace(RegExp.1, (this.getFullYear() + '').substr(4 - RegExp.1.length)); } for (var k in date) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.1, RegExp.1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length)); } } return format; } console.log(newDate.format('yyyy-MM-dd h:m:s'));
13.定义小数点后两位样式
$(function() { var priceClasses = ['price-unit', 'price-integer', 'price-point', 'price-fract'], rePrice = /([^\d]+)(\d+)(?:(\.)(\d+))?/ $('.price').replaceWith(function() { var prices = $(this).text().match(rePrice).slice(1) return prices.map(function(pricePart, i) { return pricePart ? $('<span>', { text: pricePart, class: priceClasses[i] })[0] : null }) }); })
14.用正则表达式获取地址栏某特殊字段:
方法1:'https://www.baidu.com?time=1230&user=asdk&pwd=asjdf&'.match(/\w+(?=\=\w+)/g); 输出:0:"time" 1:"user" 2:"pwd" length:3 方法2:var hrefof = window.location.href; if (hrefof.indexOf('diannaodonghua') > 0) { console.log('有这个字符') }
15.js向地址栏添加某参数及值
function addUrlPara(name, value) { var currentUrl = window.location.href.split('#')[0]; if (/\?/g.test(currentUrl)) { if (/name=[-\w]{4,25}/g.test(currentUrl)) { currentUrl = currentUrl.replace(/name=[-\w]{4,25}/g, name + "=" + value); } else { currentUrl += "&" + name + "=" + value; } } else { currentUrl += "?" + name + "=" + value; } if (window.location.href.split('#')[1]) { window.location.href = currentUrl + '#' + window.location.href.split('#')[1]; } else { window.location.href = currentUrl; } }