js 函数分类2
js 通用监听函数实现
// 把所有方法封装到一个对象里面,充分考虑兼容写法 var EventUtil = { // 添加DOM事件 addEvent: function(element, type, handler) { if(element.addEventListener) { //DOM2级 element.addEventListener(type, handler, false); }else if(element.attachEvent) { //IE element.attachEvent("on"+ type, handler); }else { element["on" + type] = handler; } }, // 移除DOM事件 removeEvent: function(element, type, handler) { if(element.removeEventListener) { //DOM2级 element.removeEventListener(type, handler, false); }else if(element.detachEvent) { //IE element.detachEvent("on"+ type, handler); }else { element["on" + type] = null; } }, // 阻止事件冒泡 stopPropagation: function(ev) { if(ev.stopPropagation) { ev.stopPropagation(); }else { ev.cancelBubble = true; } }, // 阻止默认事件 preventDefault: function(ev) { if(ev.preventDefault) { ev.preventDefaule(); }else { ev.returnValue = false; } }, // 获取事件源对象 getTarget: function(ev) { return event.target || event.srcElement; }, // 获取事件对象 getEvent: function(e) { var ev = e || window.event; if(!ev) { var c = this.getEvent.caller; while(c) { ev = c.arguments[0]; if(ev && Event == ev.constructor) { break; } c = c.caller; } } return ev; } };
js 键值对实现
<script type="text/javascript"> $(function () { var map = new Map(); map.set(1, 'name01'); map.set(2, 'name02'); console.log('map.get(1):' + map.get(1)); map.set(1, 'name0101');//更新 console.log('map.get(1):' + map.get(1)); map.remove(1);//移除 console.log('map.get(1):' + map.get(1));//返回null }) /*js键值对*/ function Map () { this.keys = new Array(); this.data = new Array(); //添加键值对 this.set = function (key, value) { if (this.data[key] == null) {//如键不存在则身【键】数组添加键名 this.keys.push(value); } this.data[key] = value;//给键赋值 }; //获取键对应的值 this.get = function (key) { return this.data[key]; }; //去除键值,(去除键数据中的键名及对应的值) this.remove = function (key) { this.keys.remove(key); this.data[key] = null; }; //判断键值元素是否为空 this.isEmpty = function () { return this.keys.length == 0; }; //获取键值元素大小 this.size = function () { return this.keys.length; }; } 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); } }; </script>
js 自定义alert提示框和confirm
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="js/jquery-1.8.2.js"></script> <style type="text/css"> .mesg-window { position: fixed; top: 40%; left: 50%; box-shadow: 1px 1px 5px 1px rgba(0,0,0,.7); background: #fff; font-size: 12px; min-width: 200px; min-height: 120px; max-width:500px; max-height:300px; display: none; margin-left: -118px; margin-top: 7px; z-index: 100; } .mesg-window .mesg-header { background: linear-gradient(#45C9BC, #28A5B9); padding: 10px; cursor: move; } .mesg-window .mesg-header .btn-close { line-height: 14px; font-size: 12px; padding: 3px 6px; border-radius: 30px; background: #262B2F; float: right; display: block; color: #fff; cursor: pointer; } .mesg-window .mesg-content { padding:10px 10px 5px 10px; text-align: center; } .mesg-window .mesg-cont { font-family: 微软雅黑; font-size: 18px; color: #666; word-wrap:break-word; } .mesg-window .mesg-content .altokbtn { background: #66cc9a; color: #fff; height: 30px; width: 60px; line-height: 30px; display: inline-block; margin-top: 10px; border-radius: 24px; text-decoration: none; } .mesg-window .mesg-content .altokbtn-confirm { background: #66cc9a; color: #fff; height: 30px; width: 60px; line-height: 30px; display: inline-block; margin-top: 10px; border-radius: 24px; text-decoration: none; margin-right:20px; } .mesg-window .mesg-content .cancelbtn-confirm { background: #aaa; color: #fff; height: 30px; width: 60px; line-height: 30px; display: inline-block; margin-top: 10px; border-radius: 24px; text-decoration: none; } </style> <script type="text/javascript"> $(function () { $('#btnAlert').click(function () { showMsg("hello,我是新的提示框!"); setTimeout("hideMsg()", 2000); }); $('#btnConfirm').click(function () { var msg = 'Hello,我是新的确认对话框!'; showConfirm(msg, function (obj) { if (obj == 'yes') { alert('你点击了确定!'); } else { alert('你点击了取消!'); } $("#mesgShow-confirm").hide(); }) }); /*关闭提示框*/ $(".btn-close").click(function () { $("#mesgShow").hide(); }); $(".altokbtn").click(function () { $("#mesgShow").hide(); }); }) /*显示消息提示框*/ function showMsg (msg) { $("#mesgShow .mesg-cont").html("").html(msg); $("#mesgShow").show(); } /*隐藏消息提示框*/ function hideMsg () { $("#mesgShow .mesg-cont").html(""); $("#mesgShow").hide(); } /*打开confirm提示框*/ function showConfirm(msg, callback) { $("#mesgShow-confirm .mesg-cont").html("").html(msg); $("#mesgShow-confirm").show(); $('.altokbtn-confirm').unbind('click').click(function () { if (callback) { callback('yes'); } }) $('.cancelbtn-confirm').unbind('click').click(function () { if (callback) { callback('no'); } }) } </script> </head> <body> <input type="button" id="btnAlert" value="Alert" /> <input type="button" id="btnConfirm" value="Confirm" /> <div class="mesg-window" id="mesgShow"> <div class="mesg-header"> <span style="color: #fff">操作提示</span><a class="btn-close right">×</a> </div> <div class="mesg-content"> <div class="mesg-cont"></div> <a href="javascript:;" class="altokbtn">确认</a> </div> </div> <div class="mesg-window" id="mesgShow-confirm"> <div class="mesg-header"><span style="color: #fff">操作提示</span></div> <div class="mesg-content"> <div class="mesg-cont"></div> <a href="javascript:;" class="altokbtn-confirm">确认</a><a href="javascript:;" class="cancelbtn-confirm">取消</a> </div> </div> </body> </html>
js 遍历json数组
var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}]; for(var o in data){ alert(o); alert(data[o]); alert("text:"+data[o].name+" value:"+data[o].age ); }
js 控制pre和div的换行
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <style type="text/css"> .inputpre { width: 500px; height: 120px; border: 1px solid #111; border-radius:5px; resize: none; padding: 5px; overflow: auto; } .inputdiv { width: 500px; height: 120px; border: 1px solid #111; border-radius:5px; resize: none; padding: 5px; overflow: auto; } </style> <script src="js/jquery-1.8.2.js"></script> <script type="text/javascript"> $(function () { $('#btnpre').click(function () { $('.inputpre').append('<div><br></div>'); set_focus($('.inputpre')); }); $('#btndiv').click(function () { $('.inputdiv').append('<div><br></div>'); set_focus($('.inputdiv')); }); }) function set_focus(el) { el = el[0]; //jquery 对象转dom对象 el.focus(); if ($.browser.msie) { var range = document.selection.createRange(); this.last = range; range.moveToElementText(el); range.select(); document.selection.empty(); //取消选中 } else { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } } </script> </head> <body> <input type="button" id="btnpre" value="pre 换行" /> <input type="button" id="btndiv" value="div 换行" /><br /> <p>pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。</p> <pre class="inputpre" contenteditable="true"></pre> <p>div 标签可以把文档分割为独立的、不同的部分。它可以用作严格的组织工具,并且不使用任何格式与其关联。</p> <div class="inputdiv" contenteditable="true"></div> </body> </html>
js 图片拖拽 图片缩放实现
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>图片缩放</title> <script src="../js/jquery-1.8.2.js"></script> <style type="text/css"> body { font-family: "Verdana", "Arial", "Helvetica", "sans-serif"; font-size: 12px; line-height: 180%; margin:0px; overflow-y:hidden;overflow-x:hidden; } .tabControl { border: 0px; } .tabControl td { font-size: 12px; line-height: 150%; } .tabControl td img { width: 20px; height: 20px; cursor: pointer; } #block1 { z-index: 10; height: 0px; left: 189px; position: absolute; top: 139px; width: 0px; } </style> <script type="text/javascript"> var drag = 0; var move = 0; var init_imgheight = 0; var init_imgwidth = 0; var init_imgleft = 0; var init_imgtop = 0; window.onload = function () { init_imgheight = images1.height; init_imgwidth = images1.width; init_imgleft = block1.style.left; init_imgtop = block1.style.top; /*IE注册事件*/ if (document.attachEvent) { document.attachEvent('onmousewheel', scrollFunc); } /*Firefox注册事件*/ if (document.addEventListener) { document.addEventListener('DOMMouseScroll', scrollFunc, false); } window.onmousewheel = document.onmousewheel = scrollFunc;//IE/Opera/Chrome } function scrollFunc(e) { if (e.wheelDelta) {//IE/Opera/Chrome if (e.wheelDelta < 0) { if (images1.height < 50 || images1.width < 50) { return false; } } images1.height += e.wheelDelta; images1.width += e.wheelDelta; } else if (e.detail) {//Firefox images1.height += e.detail; images1.width += e.detail; } } // 拖拽对象 // 参见:http://blog.sina.com.cn/u/4702ecbe010007pe var ie = document.all; var nn6 = document.getElementById && !document.all;//firefox:false,other:true var isdrag = false; var y, x; var oDragObj; function moveMouse(e) { if (isdrag) { var top = nn6 ? nTY + e.clientY - y : nTY + event.clientY - y; var left = nn6 ? nTX + e.clientX - x : nTX + event.clientX - x; $('#block1').css('top', top + "px"); $('#block1').css('left', left + "px"); return false; } } function initDrag(e) { var oDragHandle = nn6 ? e.target : event.srcElement; var topElement = "HTML"; while (oDragHandle.tagName != topElement && oDragHandle.className != "dragAble") { oDragHandle = nn6 ? oDragHandle.parentNode : oDragHandle.parentElement; } if (oDragHandle.className == "dragAble") { isdrag = true; nTY = parseInt(parseInt($('#block1').css('top')) + 0); y = nn6 ? e.clientY : event.clientY; nTX = parseInt(parseInt($('#block1').css('left')) + 0); x = nn6 ? e.clientX : event.clientX; document.onmousemove = moveMouse; return false; } } document.onmousedown = initDrag; document.onmouseup = new Function("isdrag=false"); function clickMove(s) { if (s == "up") { var top =parseInt( $('#block1').css('top')) - 100; $('#block1').css('top', top + "px"); } else if (s == "down") { var top = parseInt($('#block1').css('top')) + 100; $('#block1').css('top', top + "px"); } else if (s == "left") { var left = parseInt($('#block1').css('left')) - 100; $('#block1').css('left', left + "px"); } else if (s == "right") { var left = parseInt($('#block1').css('left')) + 100; $('#block1').css('left', left + "px"); } } function smallit() { var height1 = images1.height; var width1 = images1.width; images1.height = height1 / 1.2; images1.width = width1 / 1.2; } function bigit() { var height1 = images1.height; var width1 = images1.width; images1.height = height1 * 1.2; images1.width = width1 * 1.2; } function realsize() { images1.height = init_imgheight; images1.width = init_imgwidth; block1.style.left = init_imgleft; block1.style.top = init_imgtop; } </script> </head> <body> <div id="Layer1"> <table class="tabControl" cellspacing="2" cellpadding="0"> <tbody> <tr> <td> </td> <td><img src="http://img.jb51.net/images/map/up.gif" onclick="clickMove('up')" title="向上"></td> <td> </td> </tr> <tr> <td><img src="http://img.jb51.net/images/map/left.gif" onclick="clickMove('left')" title="向左"></td> <td><img src="http://img.jb51.net/images/map/zoom.gif" onclick="realsize();" title="还原"></td> <td><img src="http://img.jb51.net/images/map/right.gif" onclick="clickMove('right')" title="向右"></td> </tr> <tr> <td> </td> <td><img src="http://img.jb51.net/images/map/down.gif" onclick="clickMove('down')" title="向下"></td> <td> </td> </tr> <tr> <td> </td> <td><img src="http://img.jb51.net/images/map/zoom_in.gif" onclick="bigit();" title="放大"></td> <td> </td> </tr> <tr> <td> </td> <td><img src="http://img.jb51.net/images/map/zoom_out.gif" onclick="smallit();" title="缩小"></td> <td> </td> </tr> </tbody> </table> </div> <p> </p> <div id="block1" class="dragAble"> <img name="images1" src="http://img.jb51.net/images/map/760-480bsx.jpg" border="0" height="480" width="760"> </div> </body> </html>
js GUID
function GUID() { this.date = new Date(); /* 判断是否初始化过,如果初始化过以下代码,则以下代码将不再执行,实际中只执行一次 */ if (typeof this.newGUID != 'function') { /* 生成GUID码 */ GUID.prototype.newGUID = function () { this.date = new Date(); var guidStr = ''; sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16); sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16); for (var i = 0; i < 9; i++) { guidStr += Math.floor(Math.random() * 16).toString(16); } guidStr += sexadecimalDate; guidStr += sexadecimalTime; while (guidStr.length < 32) { guidStr += Math.floor(Math.random() * 16).toString(16); } return this.formatGUID(guidStr); } /* * 功能:获取当前日期的GUID格式,即8位数的日期:19700101 * 返回值:返回GUID日期格式的字条串 */ GUID.prototype.getGUIDDate = function () { return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay()); } /* * 功能:获取当前时间的GUID格式,即8位数的时间,包括毫秒,毫秒为2位数:12300933 * 返回值:返回GUID日期格式的字条串 */ GUID.prototype.getGUIDTime = function () { return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10)); } /* * 功能: 为一位数的正整数前面添加0,如果是可以转成非NaN数字的字符串也可以实现 * 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串 * 返回值: 如果符合条件,返回添加0后的字条串类型,否则返回自身的字符串 */ GUID.prototype.addZero = function (num) { if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) { return '0' + Math.floor(num); } else { return num.toString(); } } /* * 功能:将y进制的数值,转换为x进制的数值 * 参数:第1个参数表示欲转换的数值;第2个参数表示欲转换的进制;第3个参数可选,表示当前的进制数,如不写则为10 * 返回值:返回转换后的字符串 */GUID.prototype.hexadecimal = function (num, x, y) { if (y != undefined) { return parseInt(num.toString(), y).toString(x); } else { return parseInt(num.toString()).toString(x); } } /* * 功能:格式化32位的字符串为GUID模式的字符串 * 参数:第1个参数表示32位的字符串 * 返回值:标准GUID格式的字符串 */ GUID.prototype.formatGUID = function (guidStr) { var str1 = guidStr.slice(0, 8) + '-', str2 = guidStr.slice(8, 12) + '-', str3 = guidStr.slice(12, 16) + '-', str4 = guidStr.slice(16, 20) + '-', str5 = guidStr.slice(20); return str1 + str2 + str3 + str4 + str5; } } } --------------调用--------------- var guid = new GUID(); alert(guid.newGUID());