- 浏览: 6939 次
- 性别:
- 来自: 常熟
-
最新评论
收藏列表
- 全部 [32]
- md5 [1]
- javascript [17]
- eclipse [1]
- jquery [2]
- linux [1]
- sql [2]
- php [9]
- css [1]
- 导出 [1]
- excel [1]
- flash [1]
- 排序 [1]
- trim [1]
- base64 [1]
- swf [1]
- word [1]
- 前端技术 [4]
- 推送 [1]
- fullcalendar [1]
- 滑动效果 [1]
- 字符串大写首字母 [1]
- 常用js方法 [2]
- 验证格式 [1]
标题 | 标签 | 来源 | |
js控制手机摇一摇 | javascript | 利用HTML5的一个重要特性 —— DeviceOrientation来实现手机网站上的摇一摇功能 | |
<script> // DeviceOrientation将底层的方向传感器和运动传感器进行了高级封装,提供了DOM事件的支持。 // 这个特性包括两个事件: // 1、deviceOrientation:封装了方向传感器数据的事件,可以获取手机静止状态下的方向数据(手机所处的角度、方位和朝向等)。 // 2、deviceMotion:封装了运动传感器的事件,可以获取手机运动状态下的运动加速度等数据。 // 使用这两个事件,可以很能够实现重力感应、指南针等有趣的功能。 // 现在在很多Native应用中有一个非常常见而时尚的功能 —— 摇一摇,摇一摇找人、摇一摇看新闻、摇一摇找金币。。。 // 也许在android或者ios的客户端上对这个功能你已经很了解了,但是现在,我将告诉你如何在手机网页上实现摇一摇的功能。 // OK,那我们现在就开始吧,嘿嘿~ // 先来让我们了解一下设备运动事件 —— DeviceMotionEvent:返回设备关于加速度和旋转的相关信息,其中加速度的数据包含以下三个方向: // x:横向贯穿手机屏幕; // y:纵向贯穿手机屏幕; // z:垂直手机屏幕。 // 鉴于有些设备没有排除重力的影响,所以该事件会返回两个属性: // 1、accelerationIncludingGravity(含重力的加速度) // 2、acceleration(排除重力影响的加速度) // 作为码农,上代码才是最直接的,come on,代码走起! // 首先在页面上要监听运动传感事件 function init(){ if (window.DeviceMotionEvent) { // 移动浏览器支持运动传感事件 window.addEventListener('devicemotion', deviceMotionHandler, false); $("#yaoyiyaoyes").show(); } else{ // 移动浏览器不支持运动传感事件 $("#yaoyiyaono").show(); } } // 那么,我们如何计算用户是否是在摇动手机呢?可以从以下几点进行考虑: // 1、其实用户在摇动手机的时候始终都是以一个方向为主进行摇动的; // 2、用户在摇动手机的时候在x、y、z三个方向都会有相应的想速度的变化; // 3、不能把用户正常的手机运动行为当做摇一摇(手机放在兜里,走路的时候也会有加速度的变化)。 // 从以上三点考虑,针对三个方向上的加速度进行计算,间隔测量他们,考察他们在固定时间段里的变化率,而且需要确定一个阀值来触发摇一摇之后的操作。 // 首先,定义一个摇动的阀值 var SHAKE_THRESHOLD = 3000; // 定义一个变量保存上次更新的时间 var last_update = 0; // 紧接着定义x、y、z记录三个轴的数据以及上一次出发的时间 var x; var y; var z; var last_x; var last_y; var last_z; // 为了增加这个例子的一点无聊趣味性,增加一个计数器 var count = 0; function deviceMotionHandler(eventData) { // 获取含重力的加速度 var acceleration = eventData.accelerationIncludingGravity; // 获取当前时间 var curTime = new Date().getTime(); var diffTime = curTime -last_update; // 固定时间段 if (diffTime > 100) { last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.sqrt((x-last_x)*(x-last_x) + (y-last_y)*(y-last_y) + (z-last_z)*(z-last_z)) / diffTime * 10000; if (speed > SHAKE_THRESHOLD) { // TODO:在此处可以实现摇一摇之后所要进行的数据逻辑操作 count++; $("#yaoyiyaoyes").hide(); $("#yaoyiyaoresult").show(); $("#yaoyiyaoresult").html("摇你妹!第" + count + "个了!"); } last_x = x; last_y = y; last_z = z; } } </script> <div id="yaoyiyaono" style="font-size:20px;margin:10px;line-height:35px;display:none;"> 兄弟,如果您看到了我,说明您现在还不能摇,不是说您没有资格用我,而是:</br> 1、如果您使用PC机的浏览器,那可就不对了,我只爱手机浏览器;</br> 2、如果您是Android手机,那不好意思告诉你,android自带的浏览器抛弃了我,您可以用UCWeb、chrome等第三方浏览器;</br> 3、如果您都不属于以上两种情况,那我只有告诉您:您改换手机啦!!!</br> </div> <div id="yaoyiyaoyes" style="font-size:20px;margin:10px;line-height:50px;display:none;"> 兄弟,摇一个吧,说不定有一个清纯的妹子等着你呢! </div> <div id="yaoyiyaoresult" style="font-size:20px;margin:10px;line-height:50px;display:none;"></div> <script> $(document).ready(function(){ init(); }); </script> |
|||
javascript封装加减乘除 | javascript | ||
/** * 加法运算,避免数据相加小数点后产生多位数和计算精度损失。 * * @param num1加数1 | num2加数2 */ function numAdd(num1, num2) { var baseNum, baseNum1, baseNum2; try { baseNum1 = num1.toString().split(".")[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(".")[1].length; } catch (e) { baseNum2 = 0; } baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); return (num1 * baseNum + num2 * baseNum) / baseNum; }; /** * 减法运算,避免数据相减小数点后产生多位数和计算精度损失。 * * @param num1被减数 | num2减数 */ function numSub(num1, num2) { var baseNum, baseNum1, baseNum2; var precision;// 精度 try { baseNum1 = num1.toString().split(".")[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(".")[1].length; } catch (e) { baseNum2 = 0; } baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2; return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision); }; /** * 乘法运算,避免数据相乘小数点后产生多位数和计算精度损失。 * * @param num1被乘数 | num2乘数 */ function numMulti(num1, num2) { var baseNum = 0; try { baseNum += num1.toString().split(".")[1].length; } catch (e) { } try { baseNum += num2.toString().split(".")[1].length; } catch (e) { } return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum); }; /** * 除法运算,避免数据相除小数点后产生多位数和计算精度损失。 * * @param num1被除数 | num2除数 */ function numDiv(num1, num2) { var baseNum1 = 0, baseNum2 = 0; var baseNum3, baseNum4; try { baseNum1 = num1.toString().split(".")[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(".")[1].length; } catch (e) { baseNum2 = 0; } with (Math) { baseNum3 = Number(num1.toString().replace(".", "")); baseNum4 = Number(num2.toString().replace(".", "")); return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1); } }; |
|||
settimeout | javascript | ||
<script language="javascript"> function show(name) {alert("Hello World:" + name);} function _show(name) { return function() { show(name); } } setTimeout(_show(name),1000); </script> |
|||
javascript常用扩展方法 | javascript | ||
Array.prototype.indexOf = function(val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) return i; } return -1; }; Array.prototype.remove = function(val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); } }; function get_uri_arguments(){ var _get = {}, args = location.search.substr(1).split(/&/); for (var i=0; i<args.length; ++i) { var tmp = args[i].split(/=/); if (tmp[0] != "") { _get[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " ")); } } return _get; } //数字千分位处理 function format_thousand(num){ return (num+'').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,'$&,'); } |
|||
javascript base64编码 | javascript, base64 | ||
/** * * Base64 encode / decode * * @author haitao.tu * @date 2010-04-26 * @email tuhaitao@foxmail.com * */ function Base64() { // private property _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // public method for encoding this.encode = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = _utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; } // public method for decoding this.decode = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = _utf8_decode(output); return output; } // private method for UTF-8 encoding _utf8_encode = function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } // private method for UTF-8 decoding _utf8_decode = function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } |
|||
javascript摸你md5加密 | javascript, md5 | http://www.nowamagic.net/librarys/veda/detail/423 | |
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } /* * Perform a simple self-test to see if the VM is working */ function md5_vm_test() { return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; } /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the HMAC-MD5, of a key and some data */ function core_hmac_md5(key, data) { var bkey = str2binl(key); if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); var ipad = Array(16), opad = Array(16); for(var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md5(opad.concat(hash), 512 + 128); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ function str2binl(str) { var bin = Array(); var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); return bin; } /* * Convert an array of little-endian words to a string */ function binl2str(bin) { var str = ""; var mask = (1 << chrsz) - 1; for(var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); return str; } /* * Convert an array of little-endian words to a hex string. */ function binl2hex(binarray) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; } /* * Convert an array of little-endian words to a base-64 string */ function binl2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; for(var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); for(var j = 0; j < 4; j++) { if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } return str; } |
|||
placeholer支持IE,webkit | javascript | ||
function placeholerSupport(){ //判断是否支持placeholder function isPlaceholer(){ var input = document.createElement('input'); return "placeholder" in input; } //不支持的代码 if(!isPlaceholer()){ //创建一个类 function Placeholder(obj){ this.input = obj; this.label = document.createElement('label'); this.label.innerHTML = obj.getAttribute('placeholder'); this.label.style.cssText = 'position:absolute;margin-top:10px; text-indent:4px;color:#999999; font-size:12px;'; if(obj.value != ''){ this.label.style.display = 'none'; } this.init(); } Placeholder.prototype = { //取位置 getxy : function(obj){ var left, top; if(document.documentElement.getBoundingClientRect){ var html = document.documentElement, body = document.body, pos = obj.getBoundingClientRect(), st = html.scrollTop || body.scrollTop, sl = html.scrollLeft || body.scrollLeft, ct = html.clientTop || body.clientTop, cl = html.clientLeft || body.clientLeft; left = pos.left + sl - cl; top = pos.top + st - ct; }else{ while(obj){ left += obj.offsetLeft; top += obj.offsetTop; obj = obj.offsetParent; } } return{ left: left, top : top } }, //取宽高 getwh : function(obj){ return { w : obj.offsetWidth, h : obj.offsetHeight } }, //添加宽高值方法 setStyles : function(obj,styles){ for(var p in styles){ obj.style[p] = styles[p]+'px'; } }, init : function(){ var label = this.label, input = this.input, xy = this.getxy(input), wh = this.getwh(input); this.setStyles(label, {'width':wh.w, 'height':wh.h, 'lineHeight':20, 'left':xy.left, 'top':xy.top}); document.body.appendChild(label); label.onclick = function(){ this.style.display = "none"; input.focus(); } input.onfocus = function(){ label.style.display = "none"; }; input.onblur = function(){ if(this.value == ""){ label.style.display = "block"; } }; } } var inpColl = document.getElementsByTagName('input'), textColl = document.getElementsByTagName('textarea'); //html集合转化为数组 function toArray(coll){ for(var i = 0, a = [], len = coll.length; i < len; i++){ a[i] = coll[i]; } return a; } var inpArr = toArray(inpColl), textArr = toArray(textColl), placeholderArr = inpArr.concat(textArr); for (var i = 0; i < placeholderArr.length; i++){ if (placeholderArr[i].getAttribute('placeholder')){ new Placeholder(placeholderArr[i]); } } } } |
|||
swfupload示例代码 | swf, flash, javascript | ||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <head> <title>SWFUpload</title> <link href="css/default.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="swfupload/swfupload.js"></script> <script type="text/javascript" src="js/swfupload.queue.js"></script> <script type="text/javascript" src="js/fileprogress.js"></script> <script type="text/javascript" src="js/handlers.js"></script> <script type="text/javascript"> window.onload = function() { var settings = { flash_url : "swfupload/swfupload.swf",//调用flash upload_url: "../upload.php", //上传地址 post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},// file_size_limit : "100 MB",//上传最大容量 file_types : "*.*",//*.jpg file_types_description : "All Files", file_upload_limit : 3, //配置上传个数最大值 file_queue_limit : 0, custom_settings : {//bind submit and cancel progressTarget : "fsUploadProgress", cancelButtonId : "btnCancel" }, debug: false, // Button settings button_image_url: "images/hello.png", button_width: "240", button_height: "50", button_placeholder_id: "spanButtonPlaceHolder", // button_text: '<span class="theFont">浏览</span>', // button_text_style: ".theFont { font-size: 16; }", button_text_left_padding: 12, button_text_top_padding: 3, file_queued_handler : fileQueued, file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_start_handler : uploadStart, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, queue_complete_handler : queueComplete }; var swfu = new SWFUpload(settings); }; </script> </head> <body> <div id="header"> <h1 id="logo"><a href="/">SWFUpload</a></h1> <div id="version">v2.2.0</div> </div> <div id="content"> <form id="form1" action="index.php" method="post" enctype="multipart/form-data"> <p>点击“浏览”按钮,选择您要上传的文档文件后,系统将自动上传并在完成后提示您。</p> <p>请勿上传包含中文文件名的文件!</p> <div class="fieldset flash" id="fsUploadProgress"> <span class="legend">快速上传</span> </div> <div id="divStatus">0 个文件已上传</div> <div> <span id="spanButtonPlaceHolder"></span> <input id="btnCancel" type="button" value="取消所有上传" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" /> </div> </form> </div> </body> </html> |
|||
验证格式 | javascript, 常用js方法, 验证格式 | ||
//验证邮箱格式 function isEmail(strEmail) { if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true; else return false; } //验证手机或者电话格式 function checkphone(phonenumber){ var telRegExp = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;固定号码格式0512-52525252 var phoneRegExp = /^1[358]\d{9}$/;//手机号码格式13835142222 var csRegExp = /^((\d{3})-)(\d{3})(-(\d{4}))?$/;//客服号码格式400-810-8288 if (phoneRegExp.test(phonenumber) || telRegExp.test(phonenumber)||csRegExp.test(phonenumber)){ return false; }else{ return true; } } |
|||
fullcalendar使用尝试 | fullcalendar, javascript, jquery | ||
<?php gatekeeper(); $tasks = $vars['tasks']; $events_str = '[]'; if ($tasks){ $events_array = array(); foreach ($tasks as $task){ $id = $task->guid; $title = $task->title; $business_id = $task->container_guid; $start_date = date('Y-m-d H:i',$task->start_date); $end_date = date('Y-m-d H:i',$task->end_date); $priority = $task->priority; $backgroundColor = ''; switch ($priority){ case '1': $backgroundColor = '#0097F7';break; case '2': $backgroundColor = '#E8C608';break; case '3': $backgroundColor = '#E00000';break; default: $backgroundColor = '#0097F7';break; } /** * id 可选,事件唯一标识,重复的事件具有相同的 * title 必须,事件在日历上显示的title * allDay 可选,是否是整日事件 * start 必须,事件的开始时间 * end 可选,结束时间 * url 可选,当指定后,事件被点击将打开对应url * className 指定事件的样式 * editable 是否可拖拽 * source 指向次event的eventsource对象 * color 背景和边框颜色 * backgroundColor 背景颜色 * borderColor 边框颜色 * textColor 文本颜色 */ $temp = "{ id:'$id', title:'$title', business_id:'$business_id', start:'$start_date', end:'$end_date', backgroundColor:'$backgroundColor' }"; array_push($events_array, $temp); } $events_str = implode(',', $events_array); $events_str = '['.$events_str.']'; } ?> <link rel="stylesheet" type="text/css" href="<?php echo $CONFIG->wwwroot;?>mod/crm/views/default/css/fullcalendar.css"> <div id='t_calendar'></div> <script type="text/javascript"> $(document).ready(function(){ //初始化日历控件 var t_calendar = $("#t_calendar").fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"], dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"], firstDay: 1, buttonText: { today: '今天', month: '月', week: '周', day: '日' }, titleFormat:{//日历控件头部日期显示格式设置 month: 'yyyy MMMM', week: "yyyy MMM d{ '—' d}", // Sep 7 - 13 2009 day: 'yyyy,MMM d,dddd' }, columnFormat: {day: "dddd"}, timeFormat: "HH:mm{ - HH:mm}", allDayText: "全天", axisFormat: "HH:mm", firstHour: 0, allDayDefault:false,//设置默认的时间显示,为false会在任务前显示时间,为true时则不显示 editable: true, allDaySlot:false, selectable: true, selectHelper: true, unselectAuto: false, select: function(t_start, t_end){//点击空白处用于添加新的数据 var start_date = $.fullCalendar.formatDate(t_start, 'yyyy-MM-dd HH:mm'); var end_date = $.fullCalendar.formatDate(t_end, 'yyyy-MM-dd HH:mm'); var event = {start:start_date,end:end_date,allDay:false}; getAndHandleTaskForm(event,t_calendar); t_calendar.fullCalendar('unselect'); }, eventClick: function(event){//点击已有数据,用于编辑 getAndHandleTaskForm(event,t_calendar); }, eventDrop: function(event, delta,minuteDelta){//拖拉后的回调函数 changeTaskDate(event,delta,minuteDelta); }, events:<?php echo $events_str ;?> }); }); //获取task的提交页面form表单,并进行针对日历控件的处理 function getAndHandleTaskForm(event,t_calendar){ if (event.business_id == '' || event.business_id == undefined){//在日程中创建任务 getAjaxTaskForm('','',event); $('#edittask').dialog({title:'新建任务'}); }else{//在日程中编辑任务 getAjaxTaskForm(event.business_id,event.id,''); $('#edittask').dialog({title:'编辑任务'}); } $('#edittask').dialog('open'); $('#sub_task_form').hide(); $('#ajax_sub_task').show(); $('#isAjax').val(1); bindAjaxSubmitOnTaskForm(event,t_calendar); } //给获取过来的task表单绑定ajaxSubmit方法 function bindAjaxSubmitOnTaskForm(event,t_calendar){ $('#task_form').submit(function(){ $(this).ajaxSubmit({ beforeSubmit:check, url:'<?php echo $CONFIG->wwwroot;?>pg/crm/action/edittask', type:'post', dataType:'json', async:false, success:function(data){ $('#edittask').dialog('close'); if(event.business_id != undefined){//不是新建任务,移除原有的任务显示 t_calendar.fullCalendar("removeEvents",event.id); } var backgroundColor = crm_setBGcolor(data.priority); t_calendar.fullCalendar("renderEvent",{ id: data.task_id, title:data.title, business_id:data.business_id, start:event.start, end:event.end, allDay:event.allDay, backgroundColor:backgroundColor },false); } }); return false; }); $('#ajax_sub_task').click(function(){ $('#task_form').submit(); }); } //拖动任务后,改变任务的时间 function changeTaskDate(event,delta,minuteDelta){ var task_id = event.id; var url = "<?php echo $CONFIG->wwwroot;?>pg/crm/action/changeTaskDate"; var data = {task_id:task_id,delta:delta,minuteDelta:minuteDelta}; $.ajax({ url:url, data:data, type:'post', success:function(data){ if(data == 'success'){ show_message('日期修改成功! ','T'); } } }); } //根据优先级判断该输出的颜色 function crm_setBGcolor(priority){ var backgroundColor = ''; switch (priority){ case '1': backgroundColor = '#0097F7';break; case '2': backgroundColor = '#E8C608';break; case '3': backgroundColor = '#E00000';break; default: backgroundColor = '#0097F7';break; } return backgroundColor; } </script> <style type='text/css'> #t_calendar { width: 900px; margin: 0 auto; } </style> |
|||
js实现trim的方法 | javascript, trim, 常用js方法 | JS trim去空格的最佳实践 | |
if(!String.prototype.trim){ String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ''); } } |
|||
一个简单的javascript类 | javascript | ||
//这是一个构造函数,用以初始化新创建的"范围对象" //注意,这里并没有创建并返回一个对象,仅仅是初始化 function Range(from,to){//构造函数函数名首字母大写 //存放"范围对象"的起始位置和结束位置 //这连个属性石不可继承的,每个对象都拥有唯一的属性 this.from = from; this.to = to; } //原型对象定义方法,这些方法为每个范围对象所继承 (function(){ //如果x在范围内,则返回true,否则返回false //这个方法可以比较数字范围,也可以比较字符串和日期范围 this.includes = function(x){ return this.from <= x && x<= this.to; }, //对于范围内的每个数字都调用一次f //这个方法只可用做数字范围 this.foreach = function(f){ for(var x = Math.ceil(this.from);x <= this.to;x++)f(x); }, //返回表示这个范围的字符串 this.function(){ return "(" + this.from + "..." + this.to + ")"; } }).call(Range.prototype); //这里是使用"范围对象"的一些例子 var r = range(1,3);//创建一个范围对象 r.includes(2);//=>true:2在这个范围内 r.foreach(console.log);//输出1 2 3 console.log(r);//输出(1...3) |
|||
通过原型继承创建一个新对象 | javascript | ||
//inherit() 返回了一个继承自原型对象p的属性的新对象 //这里使用ECMAScript 5中的Object.create()函数 //如果不存在Object.create(),则退化使用其他方法 function inherit(p){ if(p==null) throw TypeError();//p是一个对象,但不能使null if(Object.create)//如果Object.create()存在 return Object.create(p);//直接使用它 var t = typeof p;//否则进行进一步检测 if(t !== "object" && t !== "function") throw TypeError(); function f(){};//定义一个空构造函数 f.prototype = p;//将其原型属性设置为p return new f();//使用f()创建p的继承对象 } |
|||
javascript仿java中的get,set方法 | javascript | ||
var test={ myname:"", get:myget(){ return this.myname; }, set:myset(myname){ this.myname=myname; } }; test.myset="ljqian"; test.myget; console.log(test.myget); |
|||
通过javascript控制xxx.js文件的引入 | javascript | ||
var js_page=document.createElement("script"); js_page.setAttribute("type","text/javascript"); js_page.setAttribute("src","xxx.js"); document.getElementsByTagName("head")[0].appendChild(js_page); |
|||
对浏览器地址栏hash值的监听 | javascript, 前端技术 | 不使用定时器实现的onhashchange | |
function HistoryManager() { this.listener = null; this.adapterIframe = null; this._initialize(); } ~(function() { /*设置flag的默认值为false*/ var flag = false, /*判断是否为IE浏览器*/ isIE = !!window.ActiveXObject && /msie (\d)/i.test(navigator.userAgent) ? RegExp['$1'] : false, /*使用$pointer重写该HistoryManager,以后的$pointer即为HistoryManager*/ $pointer = this; /*该方法用于在浏览器是IE,且IE版本小于8时的对历史的处理方法*/ this.makeIEHistory = function(url) { if (!url) { return ; } /*创建一个变量frameDoc来进行对Iframe框架及其子框架的处理*/ var frameDoc = $pointer.adapterIframe.contentWindow.document; /*打开一个流,以收集来自任何 document.write() 或 document.writeln() 方法的输出*/ frameDoc.open(); /*向文档写HTML代码*/ frameDoc.write([ "<html>", "<head>", "<script type='text/javascript'>", "function pageLoaded() {", "try {top.window.historyManager.fireOnHashChange(\""+url+"\");} catch(ex) {}", "}", "</script>", "</head>", "<body onload='pageLoaded();'>", "<input type='value' value='"+url+"' id='history'/>", "</body>", "</html>" ].join(""));/*join("")方法通过空字符把数组转化为字符串*/ /*设置获得的文件的title为原文件的title*/ frameDoc.title = document.title; /*关闭流*/ frameDoc.close(); } this.fireOnHashChange = function(url) { /*url字符串中用空字符代替所有除#号以外的元素,赋值给本地的hash值*/ location.hash =url.replace(/^#/, ""); /*若hash值改变了,则执行hash值改变的方法*/ if (window.onhashchange) { window.onhashchange(); } } /*该方法用于最终判断用哪种方式来处理*/ this.add = function(url) { flag = true; if (isIE && isIE < 8) { $pointer.makeIEHistory(url); } else { location.hash =url; } } /*定义fire方法,若获得的url不为空,则给url赋值当前页面url的hash值*/ this.fire = function(url) { if (!url) { url = document.location.hash.slice(1); } /*给pointer对象的listener赋值,值为url*/ $pointer.listener(url); } /*添加监听器*/ this.addListener = function(fn) { $pointer.listener = typeof fn === 'function' ? fn : function() {}; } /*初始化方法*/ this._initialize = function() { /*判断是否是IE,且IE版本是否小于8,若是,则获取id为HISTORY_ADAPTER的iframe对象,用于makeIEHistory()方法中在iframe框架中的打印方法*/ if (isIE && isIE < 8) { $pointer.adapterIframe = document.getElementById("HISTORY_ADAPTER"); $pointer.makeIEHistory(); } /*定义onhashchange方法,当hash值改变时执行*/ window.onhashchange = function() { if (flag) { flag = false; return ; } /*fire方法即为改变hash值的方法*/ $pointer.fire(); } } }).call(HistoryManager.prototype); |
|||
浏览器监听前进后退键,实现页面滑动效果 | javascript, jquery, 前端技术, 滑动效果 | ||
var FIRSTPAGEOFSLIDE="test3_1"; var LOADINGPIC="indexloading"; var xmlhttp; function S_xmlhttprequest(){ if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } /*ajax方法,mypage参数为引入的文件名XXX.XXX*/ function testInfo(mypage){ var divid=mypage.split(".")[0]; S_xmlhttprequest(); xmlhttp.open("GET",mypage,false);//ajax请求设为同步请求 xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200) { divid="div#"+divid; var newpage=xmlhttp.responseText; var mytest=$(divid); mytest.append(newpage); testcheck(divid); }else if(xmlhttp.readyState==2 && xmlhttp.status!=200){ alert("您所访问的地址不存在"); window.location.hash=""; window.location.replace("index.php"); } } xmlhttp.send(); } /*-----------------------以上为ajax的方法-----------------------------------------------------------*/ $(document).ready(function(){ /*刷新页面时判断当前hash值,根据当前hash值显示div*/ var onloadhash=getHash(); onloadhash=isHashNull(onloadhash); showpage(onloadhash); }); /*--------------为a标签绑定事件-----------------------------------------------*/ //重新创建变量nowhash用来存放当前url中的hash值 var nowhash=getHash(); //该方法用于绑定a标签的onclick事件,当a标签触发onclick事件时会把a标签的id号传到方法中,方法根据当前div与目标div进行slideleft方法的滑动 function slideonclick(a_slide){ var firstpage=nowhash; firstpage=isHashNull(firstpage); var nextpage=getNextPageid(a_slide); slideleft(firstpage,nextpage); } /*---------------向左滑动向右滑动的效果实现方法------------------------------------------------------*/ /*滑动方法,thispage为当前页面,latterpage为目标页面,animate方法为滑动方法主体*/ function slideleft(firstpage,nextpage){ var thispage="div#"+firstpage; var latterpage="div#"+nextpage; /*该if语句用于判断是否在当前页点击了当前页的a标签,如果是则不执行任何操作*/ if(thispage!==latterpage){ /*判断目标页面,根据目标页面加载相关信息*/ $("div#"+LOADINGPIC).show();//下一张页面加载之前显示loading图像 createdivforajax(nextpage);//下一张页面加载中(同步加载) $("div#"+LOADINGPIC).hide();//下一张页面加载结束,隐藏loading图像 //滑动效果开始执行 $(thispage).animate({left:"-100%"},500); $(latterpage).animate({left:"0%"},500,function(){ /*当滑动动画结束后,改变thispage的left样式,原为-100%,改变成100%*/ $(thispage).css("left","100%"); //隐藏之前的div,之前用的清空,换成隐藏可以避免每次点击都需重新调用ajax方法加载页面 $(thispage).hide(); }); //改变nowhash的值,使其一直为当前的hash值 nowhash=nextpage; } } /*该方法是右滑方法,当浏览器前进后退被点击时触发,共三个参数,第一个是当前页,第二个是下一页,第三个判断是否为加载进来的第一页*/ function slideright(firsthash,nexthash,isFirstPage){ if(isFirstPage){//判断是否为第一页,若否则执行页面滑动效果切换,若是则重置hash值 location.replace("#"); }else{ var thispage="div#"+firsthash; var formerpage="div#"+isHashNull(nexthash); $(formerpage).css("left","-100%"); createdivforajax(isHashNull(nexthash));//该算法有什么用作者也忘了。。只记得没有这个判断会出错 $(thispage).animate({left:"100%"},500); $(formerpage).animate({left:"0%"},500,function(){ $(thispage).hide(); }); //改变nowhash的值,使其一直为当前的hash值 nowhash=nexthash; } } /*--------------------hash值变化的事件监听器------------------------------------------------------------*/ /*实例化历史管理*/ var historyManager = new HistoryManager(); /*添加监听器,当事件触发时调用该方法,(hash值的改变)*/ historyManager.addListener(function() { var previoushash = arguments[0];//上一步的hash值 var isFirstPage=false;//设置变量isFirstPage,用于判断是否为第一页的boolean值,默认值为false; var presenthash=nowhash;//当前的hash值 if(presenthash==""){//当前页的hash值为空时,设置变量isFirstPage的值为true isFirstPage=true; } slideright(presenthash,previoushash,isFirstPage); }); /*通过window所有onclick事件的触发监控,来使historyManager的触发*/ document.onclick = function(ev) { ev = ev || window.event; var elem = ev.srcElement || ev.target; if (elem.tagName && elem.tagName.toLowerCase() == "a") { if (ev.preventDefault) { ev.preventDefault(); } else { ev.returnValue = false; } var href = elem.getAttribute("href", 2); historyManager.add(href); } } /*-------------------简化代码所写的方法---------------------------------------------------------*/ /*获取当前页面的hash值,根据hash值判断用户当前在哪个页面*/ function getHash(){ var myhash=document.location.hash.slice(1); return myhash; } /*判断所获取的hash值是否为空,为空则赋值test3_1*/ function isHashNull(hash){ if(hash==""||hash=="null"){ hash=FIRSTPAGEOFSLIDE; } return hash; } /*根据当前hash值跳转到url指定页面*/ function showpage(nowhash){ var nowshowpage="div#"+nowhash; createdivforajax(nowhash); $(nowshowpage).css("left","0%"); } /* 该方法用于控制调用创建新的用于存放ajax引入页面的div,调用ajax方法以及控制div的显示 通过判断div中的值是否为空判断是否加载ajax */ function createdivforajax(mydivid){ var mydiv="div#"+mydivid; var mypage=mydivid+".php"; if($(mydiv).text()=="") { createDIV(mydivid); testInfo(mypage); $(mydiv).show(); }else{ $(mydiv).show(); } } /*根据页面a标签方法返回id值来确定目标页面名*/ function getNextPageid(a_slide){ var nextpage=""; nextpage=a_slide.getAttribute("href").split("#")[1]; return nextpage; } /*创建三个方法用于生成开启slide模式下的ul标签内代码*/ function testcheck(divid){ if($(divid+" p:first").attr("checked")==="true") return; setSlide(); deletehash(); $(divid+" p:first").attr("checked","true"); } /*获取class为slide的a标签,改变a标签的属性值,href,onclick*/ function setSlide(){ var a_slide=$("a.slide"); for(i=0;i<a_slide.length;i++){//循环改变每个class值为slide的a标签的href属性以及onclick属性 var hrefvalue=a_slide.eq(i).attr("href"); if(hrefvalue.indexOf("#")>=0){//如果href的值本身就有"#"符号,即已经被调用该方法,则去除"#"符号 hrefvalue=hrefvalue.split("#")[1]; } hrefvalue="#"+hrefvalue.split(".")[0];//本身取出的href值为xxx.php,现只取xxx部分 a_slide.eq(i).attr("href",hrefvalue);//把改变的href值重新付给href属性 a_slide.eq(i).attr("onclick","slideonclick(this)");//为该a标签绑定onclick事件,调用slideonclick(this.id)事件实现左滑动效果 } } /*如果a标签的class没有slide属性,则不实现滑动效果,直接跳转*/ function deletehash(){ var a_not_slide=$("a:not(a.slide)"); for(i=0;i<a_not_slide.length;i++){ var not_slide=""; var not_slide=a_not_slide.eq(i); not_slide.click(function(){ var hrefvalue=this.getAttribute("href"); this.setAttribute("target","_blank"); window.open(hrefvalue); }); } } /*生成存放ajax方法引入的php页面的div*/ function createDIV(divid){ var newdiv='<div id="'+divid+'" style="position:absolute;left:100%"><p checked="false"></p></div>'; $("div#slideonindex").append(newdiv); } |