• 模拟Window Alert弹出框 支持拖动以及ESC键盘退出


    基本我自己封装的一些常用函数:KW.js

    JS Code:

      1 /** 
      2 @ Name : Kingwell Javascript Library 
      3 @ Author :kingwell 
      4 @ Date : 2012-8-22 
      5 @ Email : jinhua.leng##gmail.com 
      6 @ Version : 1.2 
      7 @ Update : http://kingwell-leng.iteye.com/blog/1570768 
      8 功能: 
      9 1:  $ID选择 
     10 2: 事件绑定,事件移除,获取事件目标 
     11 3: 阻止冒泡,阻止默认事件 
     12 4: 显示隐藏 
     13 5: 去除HTML 
     14 6: 去除首尾空格 
     15 7: 获取URL参数 
     16 8: Cookie操作,设置,删除,获取 
     17 9: 清除所有Cookie 
     18 10:表格排序 
     19 11: 动态转入Javascript 
     20 12: 封装Ajax 
     21 13:将HTML编码 
     22 调用方法: 
     23 KW.x(); 
     24  */  
     25 (function () {  
     26     if (!window.KW) {  
     27         window.KW = {};  
     28     };  
     29     window.KW = {  
     30         version : "1.2",  
     31         $ : function () { //$()函数  
     32             var elements = new Array();  
     33             for (var i = 0; i <= arguments.length; i++) {  
     34                 var element = arguments[i];  
     35                 //如果是一个字符串那假设它是一个ID  
     36                 if (typeof element == 'string') {  
     37                     element = document.getElementById(element);  
     38                 }  
     39                 //如果只提供了一个参数,则立即返回这个参数  
     40                 if (arguments.length == 1) {  
     41                     return element;  
     42                 }  
     43                 //否则,将它添加到数组中  
     44                 elements.push(element);  
     45             }  
     46             return elements;  
     47         },  
     48         /*-------------------- 事件处理 --------------------*/  
     49         addEvent : function (oTarget, oType, fnHandler) { //-----添加事件;  
     50             var oT = typeof oTarget == "string" ? this.$(oTarget) : oTarget;  
     51             if (!oT) {  
     52                 alert('Not found \" ' + oTarget + ' \"');  
     53                 return false  
     54             };  
     55             if (oT.addEventListener) { //for DOM  
     56                 oT.addEventListener(oType, fnHandler, false);  
     57             } else if (oT.attachEvent) { //for IE  
     58                 oT.attachEvent('on' + oType, fnHandler);  
     59             } else { //for Others  
     60                 oT['on' + oType] = fnHandler;  
     61             }  
     62         },  
     63         removeEvent : function (oTarget, oType, fnHandler) { //-----移除事件;  
     64             var oT = this.$(oTarget);  
     65             if (!oT) {  
     66                 alert('Not found \" ' + oTarget + ' \"');  
     67                 return false  
     68             };  
     69             if (oT.removeEventListener) { //for DOM  
     70                 oT.removeEventListener(oType, fnHandler, false);  
     71             } else if (oT.detachEvent) { //for IE  
     72                 oT.detachEvent('on' + oType, fnHandler);  
     73             } else { //for Others  
     74                 oT['on' + oType] = null;  
     75             }  
     76         },  
     77         getEvent : function (ev) { //-----获得事件-----  
     78             return ev || window.event;  
     79         },  
     80         getTarget : function (ev) { //-----获取目标----  
     81             return this.getEvent(ev).target || this.getEvent().srcElement;  
     82         },  
     83         stopPropagation : function () { //-----阻止冒泡-----  
     84             if (window.event) {  
     85                 return this.getEvent().cancelBubble = true;  
     86             } else {  
     87                 return arguments.callee.caller.arguments[0].stopPropagation();  
     88             }  
     89         },  
     90         stopDefault : function () { //-----阻止默认行为  
     91             if (window.event) {  
     92                 return this.getEvent().returnValue = false;  
     93             } else {  
     94                 return arguments.callee.caller.arguments[0].preventDefault();  
     95             }  
     96         },  
     97         /*-------------------- 常用函数 --------------------*/  
     98         toggleDisplay : function (id) { //-----显示,隐藏-----  
     99             var oTarget = this.$(id);  
    100             if (!oTarget) {  
    101                 return false;  
    102             }  
    103             oTarget.style.display == 'none' ? oTarget.style.display = 'block' : oTarget.style.display = 'none';  
    104         },  
    105         stripHTML : function (agr) { //-----移除HTML-----  
    106             var reTag = /<(?:.|\s)*?>/g;  
    107             return agr.replace(reTag, '')  
    108         },  
    109         stripSpace : function (oTarget) { //-----移除空格-----  
    110             var re = /^\s*(.*?)\s*$/;  
    111             return oTarget.replace(re, '$1');  
    112         },  
    113         isEmail : function (e) { //-----Is E-mail  
    114             var re = /^[a-zA-z_][a-zA-Z_0-9]*?@\w{1,}.\[a-zA-Z]{1,}/;  
    115             return re.test(e);  
    116         },  
    117         /*-------------------- Cookie操作 --------------------*/  
    118         setCookie : function (sName, sValue, oExpires, sPath, sDomain, bSecure) { //-----设置Cookie-----  
    119             var sCookie = sName + '=' + encodeURIComponent(sValue);  
    120             if (oExpires) {  
    121                 var date = new Date();  
    122                 date.setTime(date.getTime() + oExpires * 60 * 60 * 1000);  
    123                 sCookie += '; expires=' + date.toUTCString();  
    124             }  
    125             if (sPath) {  
    126                 sCookie += '; path=' + sPath;  
    127             }  
    128             if (sDomain) {  
    129                 sCookie += '; domain=' + sDomain;  
    130             }  
    131             if (bSecure) {  
    132                 sCookie += '; secure';  
    133             }  
    134             document.cookie = sCookie;  
    135         },  
    136         getCookie : function (sName) { //-----获得Cookie值-----  
    137             var sRE = '(?:; )?' + sName + '=([^;]*)';  
    138             var oRE = new RegExp(sRE);  
    139             if (oRE.test(document.cookie)) {  
    140                 return decodeURIComponent(RegExp['$1']);  
    141             } else {  
    142                 return null;  
    143             }  
    144         },  
    145         deleteCookie : function (sName, sPath, sDomain) { //-----删除Cookie值-----  
    146             this.setCookie(sName, '', new Date(0), sPath, sDomain);  
    147         },  
    148         clearCookie : function () { //清除所有Cookie  
    149             var cookies = document.cookie.split(";");  
    150             var len = cookies.length;  
    151             for (var i = 0; i < len; i++) {  
    152                 var cookie = cookies[i];  
    153                 var eqPos = cookie.indexOf("=");  
    154                 var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;  
    155                 name = name.replace(/^\s*|\s*$/, "");  
    156                 document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"  
    157             }  
    158         },  
    159         convert : function (sValue, sDataType) { //类型转,根据不同类型数据排序,比如,整型,日期,浮点,字符串,接受两个参数,一个是值,一个是排序的数据类型  
    160             switch (sDataType) {  
    161             case "int":  
    162                 return parseInt(sValue);  
    163             case "float":  
    164                 return parseFloat(sValue);  
    165             case "date":  
    166                 return new Date(Date.parse(sValue));  
    167             default:  
    168                 return sValue.toString();  
    169             }  
    170         },  
    171         geterateCompareTRs : function (iCol, sDataType) { //比较函数,用于sort排序用  
    172             return function compareTRs(oTR1, oTR2) {  
    173                 var vValue1,  
    174                 vValue2;  
    175                 if (oTR1.cells[iCol].getAttribute("value")) { //用于高级排序,比如图片,添加一个额外的属性来排序  
    176                     vValue1 = KW.convert(oTR1.cells[iCol].getAttribute("value"), sDataType);  
    177                     vValue2 = KW.convert(oTR2.cells[iCol].getAttribute("value"), sDataType);  
    178                 } else {  
    179                     vValue1 = KW.convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType);  
    180                     vValue2 = KW.convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType);  
    181                 }  
    182                 if (vValue1 < vValue2) {  
    183                     return -1;  
    184                 } else if (vValue1 > vValue2) {  
    185                     return 1;  
    186                 } else {  
    187                     return 0;  
    188                 }  
    189             }  
    190         },  
    191         tabSort : function (sTableID, iCol, sDataType) { //排序函数,sTableID为目标,iCol哪列排序,为必需,sDataType可选  
    192             var oTable = document.getElementById(sTableID);  
    193             var oTBody = oTable.tBodies[0];  
    194             var colDataRows = oTBody.rows;  
    195             var aTRs = [];  
    196             var len = colDataRows.length;  
    197             for (var i = 0; i < len; i++) {  
    198                 aTRs[i] = colDataRows[i];  
    199             };  
    200             if (oTable.sortCol == iCol) { //如果已经排序,则倒序  
    201                 aTRs.reverse();  
    202             } else {  
    203                 aTRs.sort(this.geterateCompareTRs(iCol, sDataType));  
    204             }  
    205             var oFragment = document.createDocumentFragment();  
    206             var trlen = aTRs.length;  
    207             for (var j = 0; j < trlen; j++) {  
    208                 oFragment.appendChild(aTRs[j]);  
    209             };  
    210             oTBody.appendChild(oFragment);  
    211             oTable.sortCol = iCol; //设置一个状态  
    212         },  
    213         GetQueryString : function (name) {  
    214             var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
    215             var r = window.location.search.substr(1).match(reg);  
    216             if (r != null)  
    217                 return unescape(r[2]);  
    218             return null;  
    219         },  
    220         HTMLEscape : function (str) {  
    221             var s = "";  
    222             if (str.length == 0) {  
    223                 return "";  
    224             }  
    225             s = str.replace(/&/g, "&amp;");  
    226             s = s.replace(/</g, "&lt;");  
    227             s = s.replace(/>/g, "&gt;");  
    228             s = s.replace(/ /g, "&nbsp;");  
    229             s = s.replace(/\'/g, "&#39;");  
    230             s = s.replace(/\"/g, "&quot;");  
    231             return s;  
    232         },  
    233         loadJS : function (url) {  
    234             var statu = true; //初始状态  
    235             var js = document.getElementsByTagName("script");  
    236             var len = js.length;  
    237             for (var i = 0; i < len; i++) {  
    238                 if (js[i].getAttribute("src") == url) {  
    239                     statu = false; //如果已经添加,则设置为Flase,不再添加  
    240                 }  
    241             }  
    242             if (statu) {  
    243                 var script = document.createElement("script");  
    244                 script.type = "text/javascript";  
    245                 script.src = url;  
    246                 var header = document.getElementsByTagName("head")[0];  
    247                 header.appendChild(script);  
    248                   
    249             }  
    250         },  
    251         ajax : function (obj) {  
    252             if (!obj.url) {  
    253                 return false;  
    254             };  
    255             var method = obj.type || "GET";  
    256             var async = obj.async || true;  
    257             var dataType = obj.dataType;  
    258             var XHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");  
    259             XHR.open(method, obj.url, async);  
    260             XHR.setRequestHeader('If-Modified-Since', 'Thu, 06 Apr 2006 00:00: 00 GMT');  
    261             XHR.send(null);  
    262             if (obj.sendBefore) {  
    263                 obj.sendBefore();  
    264             };  
    265             XHR.onreadystatechange = function () {  
    266                 if (XHR.readyState == 4 && (XHR.status >= 200 && XHR.status < 300 || XHR.status == 304)) {  
    267                       
    268                     if (obj.success) {  
    269                         if (dataType && dataType.toLocaleLowerCase() === "json") {  
    270                             obj.success(eval("(" + XHR.responseText + ")"))  
    271                         } else if (dataType && dataType.toLocaleLowerCase() === "xml") {  
    272                             obj.success(XHR.responseXML)  
    273                         } else {  
    274                             obj.success(XHR.responseText);  
    275                         }  
    276                     };  
    277                     if (obj.complete) {  
    278                         obj.complete()  
    279                     }  
    280                       
    281                 } else {  
    282                     if (obj.complete) {  
    283                         obj.complete()  
    284                     }  
    285                     if (obj.error) {  
    286                         obj.error("The XMLHttpRequest failed. status: " + XHR.status);  
    287                     }  
    288                       
    289                 }  
    290                   
    291             }  
    292         }  
    293           
    294     };  
    295       
    296 })();  
      1  
    169 JS Code:
    170 
    171 /*-----KW.js调用说明-----
    172 KW.$()           ----->ID选择器;
    173 addEvent         ----->绑定事件;
    174 removeEvent      ----->移除事件;
    175 getEvent         ----->获得事件;
    176 getTarget        ----->获得事件目标;
    177 stopPropagation()----->阻止冒泡
    178 stopDefault()    ----->取消默认事件
    179 
    180  */
    181 
    182 /*
    183 弹出框 函数说明
    184 alertBox(sTitle, sContent, sType);
    185 参数:
    186 sTitle:弹出框标题
    187 sContent:弹出框内容,可以是文本,HTML
    188 sType:
    189  */
    190 function alertBox(sTitle, sContent, sType) {
    191     
    192     var cl = document.createElement("div"),
    193     ac = document.createElement("div"),
    194     at = document.createElement("div"),
    195     act = document.createElement("div"),
    196     clo = document.createElement("span"),
    197     bh = document.body.offsetHeight;
    198     cl.setAttribute("id", "cover-layer");
    199     cl.setAttribute("style", "height:" + bh + "px");
    200     ac.setAttribute("id", "alert-container");
    201     at.setAttribute("id", "alert-title");
    202     act.setAttribute("class", "alert-content");
    203     clo.setAttribute("id", "alert-close");
    204     clo.setAttribute("class", "in-bl");
    205     clo.setAttribute("title", "close")
    206     
    207     cl.appendChild(ac);
    208     ac.appendChild(at);
    209     at.innerHTML = sTitle;
    210     at.appendChild(clo);
    211     ac.appendChild(act);
    212     act.innerHTML = sContent;
    213     
    214     if (sType == "prompt") {
    215         var ab = document.createElement("div"),
    216         as = document.createElement("button"),
    217         ar = document.createElement("button");
    218         ab.setAttribute("class", "alert-button");
    219         as.setAttribute("id", "alertSubmit");
    220         ar.setAttribute("id", "cancel");
    221         as.innerHTML = "Yes";
    222         ar.innerHTML = "No";
    223         ab.appendChild(as);
    224         ab.appendChild(ar);
    225         ac.appendChild(ab);
    226     }
    227     document.body.appendChild(cl);
    228     //垂直居中实现
    229     var ch = Math.ceil(document.documentElement.clientHeight / 2),
    230     lh = Math.ceil(ac.offsetHeight / 4);
    231     ac.setAttribute("style", "top:" + ch + "px;margin-top:" + -lh + "px");
    232     //响应ESC键
    233     KW.addEvent(document.body, "keyup", function () {
    234         if (KW.$("cover-layer") && KW.getEvent().keyCode == 27) {
    235             delAlert();
    236         }
    237     })
    238     if (sType == "prompt") {
    239         KW.addEvent("cancel", "click", function () {
    240             delAlert();
    241         })
    242     }
    243     if (sType == "prompt") {
    244         KW.addEvent("alertSubmit", "click", function () {
    245             delAlert();
    246             return true;
    247         })
    248     }
    249     //Drag and Drop
    250     var x;
    251     var y;
    252     var box = KW.$("alert-container");
    253     box.style.left = box.offsetLeft+"px";
    254     box.style.top = box.offsetTop+"px";
    255     KW.addEvent("alert-title", "mousedown", function () {
    256         x = KW.getEvent().clientX - parseInt(box.style.left);
    257         y = KW.getEvent().clientY - parseInt(box.style.top)
    258         KW.addEvent(document.body, "mousemove", mousemove);
    259         });
    260     document.onmouseup = function () {
    261         KW.removeEvent(document.body, "mousemove", mousemove);
    262     }
    263     function mousemove() {
    264         box.style.left= (KW.getEvent().clientX-x) + "px"
    265         box.style.top = (KW.getEvent().clientY - y) + "px"
    266     }
    267 } //alertBox End
    268 
    269 /*
    270 删除遮盖层;
    271 delAlert();
    272 当需要删除遮盖层时,调整此函数即可;
    273  */
    274 function delAlert() {
    275     KW.$("cover-layer").parentNode.removeChild(KW.$("cover-layer"));
    276 }



    CSS Code:

    1 /*-- Alert --*/
    2 #cover-layer{position:absolute; top:0; left:0; margin:auto; width:100%; height:100%; background:rgba(0,0,0,0.2); _background:#000; z-index:10000;}
    3 #cover-layer #alert-container{width:400px; position:absolute; left:50%; margin-left:-100px; top:50%; background:#FFF; box-shadow:0 0 30px rgba(0,0,0,0.6); border-radius:5px;}
    4 #cover-layer #alert-title{line-height:30px; padding:0 10px; font-weight:bold; border-top-left-radius:5px; border-top-right-radius:5px; background:#EEE; background:-moz-linear-gradient(#FFF,#EEE); background:-webkit-gradient(linear,0% 0%,0% 100%,from(#FFF),to(#EEE)); cursor:move}
    5 #cover-layer .alert-content{padding:30px 20px;}
    6 #cover-layer .alert-button{margin:auto auto 10px auto; text-align:center;}
    7 #cover-layer button{min-width:50px; margin:auto 5px}
    8 #cover-layer #alert-close{width:20px; height:20px; background:url(images/alert-delete.png) no-repeat center center; vertical-align:middle; float:right; cursor:pointer; margin:5px auto auto auto;}



    HTML Code:

     1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     2 <html xmlns="http://www.w3.org/1999/xhtml">
     3 <head>
     4 <title>kingwell</title>
     5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     6 <link rel="stylesheet" type="text/css" href="../csslibs/main.css" />
     7 
     8 </head>
     9 <body>
    10 <div style=" padding:50px">
    11 
    12     <div id="alertA">弹出框A测试 Click Me</div><br><br>
    13     <div id="alertB">弹出框B测试 Click Me</div>
    14     
    15 </div>
    16 
    17 <script type="text/javascript" src="../js/lib/KS.js"></script>
    18 
    19 <script type="text/javascript">
    20 /*----- Test AlertBox -----*/
    21 KW.addEvent("alertA", "click", function () {
    22     alertBox("System Prompt", "<div class='strong'>Alert Test !按ESC键试试</div><br><br><input type='text'><br><br><br><br><button>Save</button><button>Cancel</button>");
    23     KW.addEvent("alert-close", "click", delAlert)
    24 });
    25 
    26 KW.addEvent("alertB", "click", function () {
    27     alertBox("Prompt", "<div class='strong a-c'>Are you sure you want to delete?</div>","prompt");
    28     KW.addEvent("alert-close", "click", delAlert)
    29 });
    30 
    31 </script>
    32 </body>
    33 <html>



  • 相关阅读:
    mina 实例(转载)
    Java NIO 转载
    解决 Tomcat reload WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but fail
    ECharts的使用相关参考---转
    转-——推荐几个web中常用的一些js图表插件
    (转)Log4J日志配置详解
    ~与~+的用法
    【转】sed 高级用法
    使用sed替换一行内多个括号内的值
    【转】 SED多行模式空间
  • 原文地址:https://www.cnblogs.com/kingwell/p/2567301.html
Copyright © 2020-2023  润新知