今天发现同事前段大牛Alex写了两个js文件 方便用于 已写好的web页面突然要支持手机的, 比如有个页面所有宽度是 640px 可引入这两个js文件之后再你的页面写一句话
$(document).ready(function(){ sun.md.setViewPortContent({ initWidth : 640 }); });
之后便可以用手机看看了, 一般情况只需要很小的调整就可以了,但是有可能及特殊情况不适用, 欢迎有bug通过留言反馈
若有使用的情况特殊可以看下setViewPortContent这个方法, 主要就是根据手机类型设置它的viewport的属性 ,里面还有许多定义好的js常用方法
用此js文件如有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<l;i++){ // readyFun(); // } // readyFuns = null; // document.removeEventListener('DOMContentLoaded',DOMReady,false); // }; // sun.ready = function(fn){ // if(readyFuns.length == 0){ // document.addEventListener('DOMContentLoaded',DOMReady,false); // } // readyFuns.push(fn); // } sun.context = sun.context || {}; sun.context.getQueryStringByName = function(name) { var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i")); if (result == null || result.length < 1) { return ""; } return result[1]; }; sun.context.cookie = sun.context.cookie || {}; // article detail http://www.cnblogs.com/Darren_code/archive/2011/11/24/Cookie.html sun.context.cookie.setExpires = function (name,value,expiresValue){ var Days = expiresValue; 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(); }; sun.context.cookie.set = function (name,value){ var Days = 30; //此 cookie 将被保存 30 天 this.setExpires(name, value, Days); }; sun.context.cookie.get = function (name){ var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); if(arr != null) { return unescape(arr[2]); } return null; }; sun.context.cookie.del = function (name){ var exp = new Date(); var cval= this.get(name); exp.setTime(exp.getTime() - 1); if(cval!=null) { document.cookie= name + "="+cval+";expires="+exp.toGMTString(); } }; sun.context.localStorage = sun.context.localStorage || {}; sun.context.localStorage._ls = window.localStorage; sun.context.localStorage.set = function(name, value) { this._ls.setItem(name,value.toString()) }; sun.context.localStorage.get = function() { return this._ls.getItem(name); }; sun.context.localStorage.del = function(name) { var val = this.get(name); if (!!val) { this.__ls.removeItem("c"); } }; sun.context.localStorage.clearAll = function() { window.localStorage.clear() }; //----------------------------- undealed ----------------------------------- function addEvent (type, element, fun) { if (element.addEventListener) { addEvent = function (type, element, fun) { element.addEventListener(type, fun, false); } } else if(element.attachEvent){ addEvent = function (type, element, fun) { element.attachEvent('on' + type, fun); } } else{ addEvent = function (type, element, fun) { element['on' + type] = fun; } } return addEvent(type, element, fun); } sun.util = sun.util || {}; sun.util.array = sun.util.array || {}; /** * @param => ([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 '<span>I am Hero!</span>' * @return '<span>I am Hero!</span>' */ sun.util.htmlDecode = function(html) { var a = document.createElement( 'a' ); a.innerHTML = html; return a.textContent; }; /** * * @param '<span>I am Hero!</span>' * @return '<span>I am Hero!</span>' */ 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 http://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 }
// <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">
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);
相关推荐
本页面被请求时发生在web page生命周期之前, 当有一个页面被请求时,ASP.NET引擎要判断一下这个页面是否需要经过编译或者直接通过此页面的缓冲版本直接发给请求者。 2. Start 在这阶段,Page的Request,Response...
请在web.xml文件中使用– page >元素为整个web应用程序设置错误处理页面。已知:处理状态码为404的页面为404.jsp,处理状态码为500的页面为500.jsp。
本文介绍了ionic2屏幕适配实现适配手机、平板等设备的示例代码,分享给大家,具体如下: 推荐使用的编辑器是:VS code (Visual Studio Code)=>只负责编辑文档,不编译。 而WebStorm 有检查编译等,在ionic1开发...
WebPageMaker. 自己动手做网页 WebPageMaker. 自己动手做网页
Single page web applications are your next step: pushing UI rendering and business logic to the browser and communicating with the server only to synchronize data, they provide a smooth user ...
开放时代从Web_Page到Web_App
JAVA的Web打印方式,主要使用PageOffice、POI、jacob,html打印等方式来进行。
web页面截图工具。 用法 首先安装NodeJS和NPM 。 git clone git@github.com:yutingzhao1991/web-screenshot.git cd web-screenshot npm install npm start 然后使用可以访问以获得iqiyi主页的屏幕截图。 原料药 /...
Web Page Maker 印心绿色注册版 菜鸟级的html编辑器,像vb一样拖拽。
web page maker V3.12 注册码 随便输入用户名 注册一下,绿化版
eclipse 3.7 indigo web页面编辑插件,包含jsp html css等
鉴于市场上用户的手机型号、种类、屏幕分辨率等参差不齐,传统方式根据主流系统分别开发相应的系统耗时又耗力,为了高效开发并节约开发项目成本,本文采用Android+HTML5相结合的方式进行移动端Web系统的设计研发工作...
JSP里web.xml实现错误处理页面的制作404,和500
web page maker是一款简化但功能十足的网页制作工具,非常容易上手,能满足个人使用的需要 所见即所得,不需要html语言底子,很好用,推荐
首先引入一个WebBrowser在需要打印的页面,可以直接添加: 复制代码 代码如下: <object id="WebBrowser" classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height="0" width="0"> </object> 2 ...
Web Page Maker 是一个易于使用的网页编辑器,它可以使你在几分 钟内就创建并上传你的网页,并且不需要你了解任何关于 HTML 的知识。 这是汉化版,无需原版,安装即可使用!
一种超简单的有效的在网页中嵌入Word方法
Web Page Maker 3.12 中文,带注册机。破解过程:解压到一个目录下,打开注册机keygen.exe,点击keygen按钮生成注册码,点击copy按钮复制注册码。然后,打开软件,会提示你使用试用版还是注册,点击注册,点击使用...
Web Page Maker 是一个易于使用的网页编辑器,它可以使你在几分 钟内就创建并上传你的网页,并且不需要你了解任何关于 HTML 的知识。 你只需要拖曳对象到页面中并随意的调整