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. iOS-技术细节整理

    遇到未使用类,可以看看xcode->help->developer documentation 下面做一下简单的技术细节整理 Auto Layout使用Auto Layout来灵活改变UI ...

  2. 使用idea工具开发webservice

    在idea开发工具中使用axis2插件创建集成webservice的web项目: 一.创建java项目                  二.添加webservices支持 在红线框2处选择要使用的w ...

  3. POJ 2135 Farm Tour(最小费用最大流)

    Description When FJ's friends visit him on the farm, he likes to show them around. His farm comprise ...

  4. CodeForces Round #521 (Div.3) D. Cutting Out

    http://codeforces.com/contest/1077/problem/D You are given an array ss consisting of nn integers. Yo ...

  5. Chromium学习笔记

    1. How to build chromium Follow the steps on:http://www.chromium.org/Home 需要安装Win7 x64的OS,PC的配置尽可能高端 ...

  6. 服务器下面的WEB-INF 不能直接访问,可以通过servlet进行访问

    服务器下面的WEB-INF 不能直接访问,可以通过servlet进行访问

  7. BZOJ4448 SCOI2015情报传递(离线+树链剖分+树状数组)

    即滋磁单点修改,询问路径上小于某数的值有多少个.暴力树剖套个主席树(或者直接树上主席树,似乎就1个log了?感觉不一定比两个log快)即可,然而不太优美. 开始觉得可以cdq,然而就变成log^3了. ...

  8. dva的基本用法

    dva是一个状态管理工具,整合了redux,redux-saga,react-router,fetch等框架,目前只能用于react的状态管理 1. dva的models dva的主要作用还是整合了r ...

  9. JSONP以及Spring对象MappingJacksonValue的使用方式

    什么是JSONP?,以及Spring对象MappingJacksonValue的使用方式 原文: https://blog.csdn.net/weixin_38111957/article/detai ...

  10. [hdu 4348]区间修改区间查询可持久化线段树

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4348 一开始把lazy标记给push_down了,后来发现这样会让持久化变乱,然后想到不用push_d ...