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(), );
sexadecimalTime = this.hexadecimal(this.getGUIDTime(), );
for (var i = ; i < ; i++) {
guidStr += Math.floor(Math.random() * ).toString();
}
guidStr += sexadecimalDate;
guidStr += sexadecimalTime;
while (guidStr.length < ) {
guidStr += Math.floor(Math.random() * ).toString();
}
return this.formatGUID(guidStr);
}
/* * 功能:获取当前日期的GUID格式,即8位数的日期:19700101 * 返回值:返回GUID日期格式的字条串 */
GUID.prototype.getGUIDDate = function () {
return this.date.getFullYear() + this.addZero(this.date.getMonth() + ) + 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() / ));
}
/* * 功能: 为一位数的正整数前面添加0,如果是可以转成非NaN数字的字符串也可以实现 * 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串 * 返回值: 如果符合条件,返回添加0后的字条串类型,否则返回自身的字符串 */
GUID.prototype.addZero = function (num) {
if (Number(num).toString() != 'NaN' && num >= && num < ) {
return '' + 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(, ) + '-', str2 = guidStr.slice(, ) + '-', str3 = guidStr.slice(, ) + '-', str4 = guidStr.slice(, ) + '-', str5 = guidStr.slice();
return str1 + str2 + str3 + str4 + str5;
}
}
} --------------调用--------------- var guid = new GUID(); alert(guid.newGUID());

js 函数分类2的更多相关文章

  1. (转)js函数参数设置默认值

    原文:http://www.cnblogs.com/RightDear/archive/2013/06/26/3156652.html js函数参数设置默认值   php有个很方便的用法是在定义函数时 ...

  2. 如何编写高质量的 JS 函数(2) -- 命名/注释/鲁棒篇

    本文首发于 vivo互联网技术 微信公众号 链接:https://mp.weixin.qq.com/s/sd2oX0Z_cMY8_GvFg8pO4Q作者:杨昆 上篇<如何编写高质量的 JS 函数 ...

  3. 如何编写高质量的 JS 函数(3) --函数式编程[理论篇]

    本文首发于 vivo互联网技术 微信公众号 链接:https://mp.weixin.qq.com/s/EWSqZuujHIRyx8Eb2SSidQ作者:杨昆 [编写高质量函数系列]中, <如何 ...

  4. 3.3 js函数

    1.函数语法: 函数声明的方式:function 函数名(参数1,参数2-){//函数体;}函数调用:函数名(参数1,参数2-); 函数内不一定都指定返回值. 如果需要指定返回值,可用 return ...

  5. Js函数function基础理解

    正文:我们知道,在js中,函数实际上是一个对象,每个函数都是Function类型的实例,并且都与其他引用类型一样具有属性和方法.因此,函数名实际上是指向函数对象的指针,不与某个函数绑定.在常见的两种定 ...

  6. js函数表达式和函数声明的区别

    我们已经知道,在任意代码片段外部添加包装函数,可以将内部的变量和函数定义"隐 藏"起来,外部作用域无法访问包装函数内部的任何内容. 例如: var a = 2; function ...

  7. 通用js函数集锦<来源于网络> 【二】

    通用js函数集锦<来源于网络> [二] 1.数组方法集2.cookie方法集3.url方法集4.正则表达式方法集5.字符串方法集6.加密方法集7.日期方法集8.浏览器检测方法集9.json ...

  8. 通用js函数集锦<来源于网络/自己> 【一】

    通用js函数集锦<来源于网络/自己>[一] 1.返回一个全地址2.cookie3.验证用户浏览器是否是微信浏览器4.验证用户浏览器是否是微博内置浏览器5.query string6.验证用 ...

  9. 100多个基础常用JS函数和语法集合大全

    网站特效离不开脚本,javascript是最常用的脚本语言,我们归纳一下常用的基础函数和语法: 1.输出语句:document.write(""); 2.JS中的注释为//3.传统 ...

随机推荐

  1. c# 生成dll

    进入项目属性栏里,选择输出类型为类库.

  2. 软工实践 - 第二十四次作业 Beta 冲刺(2/7)

    队名:起床一起肝活队 组长博客:https://www.cnblogs.com/dawnduck/p/10105380.html 作业博客:班级博客本次作业的链接 组员情况 组员1(队长):白晨曦 过 ...

  3. lintcode-83-落单的数 II

    83-落单的数 II 给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字. 样例 给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4 挑战 一次遍历,常数级 ...

  4. ArcGIS Engine开发中利用GP工具时常出现的错误

    在用GP工具的时候常常会碰到这个错误: 调用 GP 对 COM 组件的调用返回了错误 HRESULT E_FAIL 解决方案: 这种情况一般有两种可能. 1.AE程序的license的级别不够. 2. ...

  5. [剑指Offer] 27.字符串的排列

    [思路]从第一位开始,判断每一位字符的所有可能性,依此递归. class Solution { public: void PermutationHelp(vector<string> &a ...

  6. 无人值守安装linux系统

    需要使用到的服务:PXE + DHCP+TFTP+ Kickstart+ FTP KickStart是一种无人职守安装方式 执行 PXE + KickStart安装需要准备内容:  • DHCP 服务 ...

  7. [poj 3693]后缀数组+出现次数最多的重复子串

    题目链接:http://poj.org/problem?id=3693 枚举长度L,看长度为L的子串最多能重复出现几次,首先,能出现1次是肯定的,然后看是否能出现两次及以上.由抽屉原理,这个子串出现次 ...

  8. 工作总结-js插件

    因最近工作需要,使用了一些js插件,感觉还不错,记录下来以便以后使用. 1.图片轮播插件: 扩展:梦想天空系列:http://www.cnblogs.com/lhb25/archive/2013/01 ...

  9. 团队代码中Bug太多怎么办?怎样稳步提高团队的代码质量

    最近负责的Android APP项目,由于团队成员变动.界面改版导致代码大幅修改等原因,产品发布后屡屡出现BUG导致的程序崩溃. 经过对异常统计和代码走读,BUG主要集中在空指针引起的NullPoin ...

  10. dbcp基本配置和重连配置

    转载自:http://agapple.iteye.com/blog/772507 最近在看一些dbcp的相关内容,顺便做一下记录,免得自己给忘记了. 1. 引入dbcp (选择1.4) Java代码  ...