核心提示:今天发现同事前段大牛Alex写了两个js文件 方便用于 已写好的web页面突然要支持手机的, 比如有个页面所有宽度是 640px可引入这两个js文件之后再你的页面写一句话 $(document).r...
今天发现同事前段大牛Alex写了两个js文件 方便用于 已写好的web页面突然要支持手机的, 比如有个页面所有宽度是 640px 可引入这两个js文件之后再你的页面写一句话
$(document).ready(function(){ sun.md.setViewPortContent({ initWidth : 640 }); });
之后便可以用手机看看了, 一般情况只需要很小的调整就可以了,但是有可能及特殊情况不适用, 欢迎有bug通过留言反馈
若有使用的情况特殊可以看下setViewPortContent这个方法, 主要就是根据手机类型设置它的viewport的属性 , 里面还有许多定义好的js常用方法
用此s文件如有bug等等问题带来利益损失概不负责
下面是js代码引入要有顺序 先引入sun.js 再引入sun.md.js, (这两个文件时在jquery下写的所以jquery必须最先引入)
sun.js
var sun = sun || {}; /** * it is for alex to shortcut method * delete before online */ (function shortCut() { tojs = function(vmodel) { return ko.mapping.toJS(vmodel) }; log = function (){ console.log(arguments) }; write = function(txt){ var p = document.createElement('p'); var hr = document.createElement('hr'); p.innerHTML = txt; document.body.appendChild(hr); document.body.appendChild(p); }; })() sun.ajax = function() { var mime = { html: 'html', js: 'script', json: 'json', xml: 'xml', txt: 'text' } var _stringifyData = function(sType, oData) { var _data = oData; if ((sType.toUpperCase() === 'POST') && ( !! oData)) { _data = JSON.stringify(oData); } return _data; }; base = function(sUrl, sType, sDataType, oData, fnCallBack, isShlowLoading, isAsync) { var _data = oData, _isAsync = typeof isAsync === 'boolean' ? isAsync : true; if (sUrl.indexOf('?') === -1){ sUrl = sUrl + '?t=' + Math.random(); }else { sUrl = sUrl + '&t=' + Math.random(); } $.ajax({ async: _isAsync, type: sType, url: sUrl, data: _stringifyData(sType, oData), contentType: 'application/json', dataType: sDataType, beforeSend: function(XMLHttpRequest) { if (!!isShlowLoading) { } }, success: function(data, textStatus) { if (!!isShlowLoading) { } if(!_isAsync && (typeof fnCallBack === 'function')){ fnCallBack(data, textStatus); }; _data = data; }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (!!isShlowLoading) { } _data = errorThrown; } }).done(function(data, textStatus, _self) { if (!!isShlowLoading) { } if (!!_isAsync && (typeof fnCallBack === 'function')) { fnCallBack(data, textStatus); } });; return _data; }; return { post: function(sPageUrl, oData, fnCallBack, isAsync) { if ((typeof oData === 'function') && (!fnCallBack)) { fnCallBack = oData; oData = null; } return base(sPageUrl, 'POST', mime.json, oData, fnCallBack, false, isAsync); }, getJSON: function(sPageUrl, oData, fnCallBack, isAsync) { if ((typeof oData === 'function') && (!fnCallBack)) { fnCallBack = oData; oData = null; } return base(sPageUrl, 'get', mime.json, oData, fnCallBack, false, isAsync); } } }(); sun.$ = function(query) { return document.querySelectorAll(query); }; // var __readyFuns = []; // function DOMReady(){ // for(var i=0,l=readyFuns.length;i([1,2,32,4]) * return [1, 2, 4, 32] * * @param => ([1,2,32,4], false) * return [32, 4, 2, 1] * */ sun.util.array.sort = function(arrayList, isAsc) { if (typeof isAsc != 'boolean') { isAsc = true; } function sortNumber(a, b) { if (!!isAsc) { return a - b } else { return b - a } } return arrayList.sort(sortNumber); }; /** * @param => ([0,1,2,3,4,5,6,7,8,9], 6) * return [0, 1, 2, 3, 4, 5, 7, 8, 9] * * @param => ([0,1,2,3,4,5,6,7,8,9], [2,6,8]) * return [0, 1, 3, 4, 5, 7, 9] * */ sun.util.array.remove = function(arrayList, n) { //prototype为对象原型,注意这里为对象增加自定义方法的方法。 if ( n < 0 || typeof n === 'undefined') { return arrayList; } else if (sun.util.isArray(n)) { var _tmp = null; n = this.sort(n, false); for(index in n) { arrayList = this.remove(arrayList, n[index]); } return arrayList; } else { return arrayList.slice(0,n).concat(arrayList.slice(n+1,arrayList.length)); } /* concat方法:返回一个新数组,这个新数组是由两个或更多数组组合而成的。 这里就是返回arrayList.slice(0,n)/arrayList.slice(n+1,arrayList.length) 组成的新数组,这中间,刚好少了第n项。 slice方法: 返回一个数组的一段,两个参数,分别指定开始和结束的位置。 */ }; /** * format number * e.g. 12000 => 1,2000 * @param amtStr number * @return string */ sun.util.formatIntNum = function (amtStr) { var isInt = function (num) { return (num % 1 === 0) }; var amtStr = (isInt(amtStr)) ? amtStr : Number(amtStr).toFixed(0); amtStr = "" + amtStr; var a, renum = ''; var j = 0; var a1 = '', a2 = '', a3 = ''; var tes = /^-/; var isCurrency = (typeof (isCurrency) != 'undefined') ? isCurrency : true; a = amtStr.replace(/,/g, ""); a = a.replace(/[^-\.,0-9]/g, ""); a = a.replace(/(^\s*)|(\s*$)/g, ""); if (tes.test(a)) a1 = '-'; else a1 = ''; a = a.replace(/-/g, ""); if (a != "0" && a.substr(0, 2) != "0.") a = a.replace(/^0*/g, ""); j = a.indexOf('.'); if (j < 0) j = a.length; a2 = a.substr(0, j); a3 = a.substr(j); j = 0; for (i = a2.length; i > 3; i = i - 3) { renum = "," + a2.substr(i - 3, 3) + renum; j++; } renum = a1 + a2.substr(0, a2.length - j * 3) + renum + a3; return renum; } /** * format number of money. * e.g. 12000.235 => 12,000.24 * @param amtStr number * @return string */ sun.util.formatFloat = function (amtStr, isCurrency) { var isInt = function (num) { return (num % 1 === 0); }; var amtStr = (isInt(amtStr)) ? amtStr : Number(amtStr).toFixed(2); amtStr = "" + amtStr; var a, renum = ''; var j = 0; var a1 = '', a2 = '', a3 = ''; var tes = /^-/; var isCurrency = (typeof (isCurrency) != 'undefined') ? isCurrency : true; var subfix = (isInt(amtStr) && isCurrency) ? '.00' : ''; a = amtStr.replace(/,/g, ""); a = a.replace(/[^-\.,0-9]/g, ""); a = a.replace(/(^\s*)|(\s*$)/g, ""); if (tes.test(a)) a1 = '-'; else a1 = ''; a = a.replace(/-/g, ""); if (a != "0" && a.substr(0, 2) != "0.") a = a.replace(/^0*/g, ""); j = a.indexOf('.'); if (j < 0) j = a.length; a2 = a.substr(0, j); a3 = a.substr(j); j = 0; for (i = a2.length; i > 3; i = i - 3) { renum = "," + a2.substr(i - 3, 3) + renum; j++; } renum = a1 + a2.substr(0, a2.length - j * 3) + renum + a3 + subfix; return renum; } sun.util.isEven = function(num) { return num % 2 == 0 ? true : false; }; /** * @param => ([]) * return true * * * @param => ({}) * return false * */ sun.util.isArray = function(arg) { // first way: return Object.prototype.toString.call(arg) === '[object Array]'; // second way: //return (arr instanceof Array); }; /** * * eg. format = 'yyyy-MM-dd hh:mm:ss' * */ sun.util.getCurrentTime = function(format) { var _this = new Date(); var o = { "M+": _this.getMonth() + 1, //month "d+": _this.getDate(), //day "h+": _this.getHours(), //hour "m+": _this.getMinutes(), //minute "s+": _this.getSeconds(), //second "q+": Math.floor((_this.getMonth() + 3) / 3), //quarter "S": _this.getMilliseconds() //millisecond } if(!format) { format = "yyyy-MM-dd hh:mm:ss"; } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (_this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; }; /** * * @param 'I am Hero!' * @return 'I am Hero!' */ sun.util.htmlDecode = function(html) { var a = document.createElement( 'a' ); a.innerHTML = html; return a.textContent; }; /** * * @param 'I am Hero!' * @return 'I am Hero!' */ sun.util.htmlEncode = function ( html ) { return document.createElement( 'a' ).appendChild( document.createTextNode( html ) ).parentNode.innerHTML; }; sun.util.parseToInt = function(obj, defaultNum, radix){ var _t = 0; if (typeof radix != 'number'){ radix = 10; } _t = parseInt(obj, radix); if (!_t){ _t = defaultNum; } return _t; }; /** * @param => ('I am a boy', 'boy', 'girl') * return 'I am a girl' * enhance replace * @param oString string * @param AFindText string * @param ARepText string * @return string */ sun.util.replaceAll = function (oString, AFindText, ARepText) { var raRegExp = new RegExp(AFindText.replace(/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g, "\\$1"), "ig"); return oString.replace(raRegExp, ARepText); }; /** * @param => ('best {0} for {1}', 'wish', 'you') * return 'best wish for you' */ sun.util.stringFormat = function(txt) { var arg = arguments, matchResult, matLength, str = txt, reg = /\{\d+?\}/gmi, i; matchResult = str.match(reg); if (matchResult) { matLength = matchResult.length; if (arg.length >= matLength) { for (i = 0; i < matLength; i++) { str = str.replace(matchResult[i], arg[i + 1]); } } } return str; }; sun.util.transforTime = function (time) { var date = parseInt(time); var weekdays = ["Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]; var result = ""; result += weekdays[new Date(date).getDay()]; result += " "; result += months[new Date(date).getMonth()]; result += " "; result += new Date(date).getDate(); result += " "; result += new Date(date).getFullYear(); result += " "; result += new Date(date).getHours(); result += ":"; result += new Date(date).getMinutes(); return result; };
sun.md.js
sun = sun || {}; sun.md = (function(global){ var self, _userAgent = navigator.userAgent, _rWins = /Windows/i, _rWP = /IEMobile/i, _rAndroid = /Android/i, _rIPhone = /iPhone/i; androidScreenPixelRatio = { pr : null, screenHeight : null, getScreenHeight : function() { var that = this; if (null == that.screenHeight) { that.screenHeight = (screen.width < screen.height) ? screen.height : screen.width; } return that.screenHeight; }, getDpi : function() { var that = this, dpi = 320; if (1200 <= that.getScreenHeight()) { dpi = "device-dpi"; } return dpi; }, getPixelRatio : function() { var that = this; if (null == that.pr) { that.pr = window.devicePixelRatio; } return that.pr; }, judgePixelRatio : function(pr) { var that = this; return (pr === that.getPixelRatio()); }, isLdpi : function() { var that = this; return that.judgePixelRatio(0.75); }, isMdpi : function() { var that = this; return that.judgePixelRatio(1); }, isHdpi : function() { var that = this; return that.judgePixelRatio(1.5); } }; BOMHeight = function() { var pageHeight = window.innerHeight; if(typeof pageHeight != "number"){ if(document.compatMode == "CSS1Compat"){ pageHeight = document.documentElement.clientHeight; }else{ pageHeight = document.body.clientHeight; } } return pageHeight; }; _parseViewPortContent = function(initWidth, initHeight, isUserScale, initScale, minScale, maxScale, isIntelligence) { var w = !!initWidth ? initWidth : "100%", h = !!initHeight ? initHeight : BOMHeight(), isUserScale = !!isUserScale ? 'yes' : 'no', initScale = !!initScale ? initScale : 1.0, //最大极限是 1.69 minScale = !!minScale ? minScale : 0.1, maxScale = !!maxScale ? maxScale : 1.0, domeMeta = '', targetDensitydpi = 'device-dpi', // [dpi_value(70 - 400) | device-dpi | high-dpi | medium-dpi | low-dpi] clientW = document.documentElement.clientWidth, screenW = window.screen.width; if (w === '100%') { w = "device-width"; initScale = 1.0; targetDensitydpi = 'device-dpi'; if (!!isIntelligence) { initScale = (screenW/clientW).toFixed(4); if(self.isAndroid()) { targetDensitydpi = 'device-dpi'; } } } if (typeof w === 'number') { if (!!isIntelligence) { w = Math.max(w, screenW); } initScale = (screenW/w).toFixed(4); if(self.isAndroid()) { initScale = 1; targetDensitydpi = (w/2.25714).toFixed(4); if (targetDensitydpi < 70) { targetDensitydpi = 70; } if (targetDensitydpi > 400) { targetDensitydpi = 400; } } } domeMeta = 'width=' + w + //', height=' + h + ', minimum-scale=' + minScale + ', maximum-scale=' + maxScale + ', initial-scale=' + initScale + ', user-scalable=' + isUserScale + ', target-densitydpi=' + targetDensitydpi; return domeMeta.trim(); }; _getScreen = function(){ // detail information to https://www.cnblogs.com/tearer/archive/2010/09/06/1819471.html // window.devicePixelRatio = 物理像素 / dips // window.screen.width = Android设备返回的是物理像素宽,IOS =》 dips宽 var s = "网页可见区域宽:" + document.body.clientWidth + "\n"; s += " 网页可见区域高:" + document.body.clientHeight + "\n"; s += " 网页可见区域宽:" + document.body.offsetWidth + " (包括边线和滚动条的宽)" + "\n"; s += " 网页可见区域高:" + document.body.offsetHeight + " (包括边线的宽)" + "\n"; s += " 网页正文全文宽:" + document.body.scrollWidth + "\n"; s += " 网页正文全文高:" + document.body.scrollHeight + "\n"; s += " 网页被卷去的高(ff):" + document.body.scrollTop + "\n"; s += " 网页被卷去的高(ie):" + document.documentElement.scrollTop + "\n"; s += " 网页被卷去的左:" + document.body.scrollLeft + "\n"; s += " 网页正文部分上:" + window.screenTop + "\n"; s += " 网页正文部分左:" + window.screenLeft + "\n"; s += " 屏幕分辨率的高:" + window.screen.height + "\n"; s += " 屏幕分辨率的宽:" + window.screen.width + "\n"; s += " 屏幕可用工作区高度:" + window.screen.availHeight + "\n"; s += " 屏幕可用工作区宽度:" + window.screen.availWidth + "\n"; s += " 你的屏幕设置是 " + window.screen.colorDepth + " 位彩色" + "\n"; s += " 物理像素/独立像素比: " + window.devicePixelRatio + " 像素/英寸" + "\n"; s += " 你的屏幕设置 " + window.screen.deviceXDPI + " 像素/英寸" + "\n"; return s; }; self = {}; self.userAgent = _userAgent; //self.screen = _getScreen(); self.getViewPortContent = function() { var domeMeta = document.getElementsByName('viewport')[0]; return domeMeta.content; }; // var options = { // initWidth: null, // initHeight: null, // isUserScale: null, // initScale: null, // minScale: null, // maxScale: null, // isIntelligence: bool /default null // } // default options likes: { initWidth : '100%' } or { initWidth : 540 } // self.setViewPortContent = function (options) { var DOM_meta = document.getElementsByName('viewport')[0], _content = ''; if (!DOM_meta) { DOM_meta = document.createElement('meta'); DOM_meta.name = 'viewport'; document.head.appendChild(DOM_meta); } if (typeof options === 'string'){ _content = _content; } else if (typeof options === 'object') { _content = _parseViewPortContent(options.initWidth, options.initHeight, options.isUserScale, options.initScale, options.minScale, options.maxScale, options.isIntelligence); } else { _content = _parseViewPortContent(); } DOM_meta.content = _content; }; self.isAndroid = function () { var me = this, result = false; if((_userAgent.match(_rAndroid))&& (_userAgent.match(_rAndroid).length > 0)) { result = true; } return result; }; self.isWindows = function () { var me = this, result = false; if((_userAgent.match(_rWins)) && (_userAgent.match(_rWins).length > 0)) { result = true; } return result; }; self.isWinPhone = function () { var me = this, result = false; if((_userAgent.match(_rWP)) && (_userAgent.match(_rWP).length > 0)) { result = true; } return result; }; self.isIOS = function () { var me = this, result = false; if((_userAgent.match(_rIPhone))&& (_userAgent.match(_rIPhone).length > 0)) { result = true; } return result; }; return self; })(this);