贡献一个JS的弹出框代码.

【原创】贡献一个JS的弹出框代码...

一.前言

最近在做一个项目,自己感觉系统自带的alert()方法的弹出框实在是不堪入目,所以在网上找了一些资料,然后自己加工了一下,做出了自己的一个js弹出框,在这里贡献出来,希望对你有帮助.

二.开始

在这里我们来一个获取验证码的页面来说明,也是在我项目用用到的一个页面。我们首先创建一个HTML的静态页面。其中代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>自定义提示</title>
<script src="jquery-1.8.3.js" type="text/javascript"></script>
<script src="sAlter.js" type="text/javascript"></script>
<link href="GetRelationByPhone.css" rel="stylesheet" type="text/css" />
</head>

<body>
 <div>
      <form id="form1" action="#" method="post">
        <div>
            <section class="infos">
            <label class="fLeft">手机号</label>
            <input type="hidden" value="oLlIXuNocl66hPYHHt8vwAOLhWTA" name="openid" />
            <span class="commeInput"><input type="text" class="no-border" name="phone" id="phone" value="" placeholder="请输入您的手机号"/>
            </span>
            <em id="mob" class="yg-input-close rt12"></em></section>

            <section class="infos no-boder">
            <label class="fLeft">验证码</label>
            <span class="commeInput"><input type="text" class="no-border2" name="code" id="code" value="" placeholder="请输入验证码"  />
            <input type="button" id="btn"  class="btn_mfyzm" value="获取验证码"  onclick="getverify()"    />
            </span>
            <em id="mob2" class="yg-input-close lt50"></em></section>
            <div><button type="button" class="btn-pay" onclick="go()"  title="确定">确&nbsp &nbsp 定</button></div>
        </div>
      </form>
</div>
</body>
</html>
sAlter.js就是我们封装过后的js。我们先看看使用的效果:

贡献一个JS的弹出框代码.

贡献一个JS的弹出框代码.

 来看看我们的页面js代码如下:

<script type="text/javascript">

    function timer(time) {
        var btn = $("#btn");
        btn.attr("disabled", true);  //按钮禁止点击
        btn.val(time <= 0 ? "发送验证码" : ("" + (time) + ""));
        var hander = setInterval(function () {
            if (time <= 0) {
                clearInterval(hander); //清除倒计时
                btn.val("发送验证码");
                btn.attr("disabled", false);
                return false;
            } else {
                btn.val("" + (time--) + "");
            }
        }, 1000);
    }


    //绑定手机号码
    function go() {

        var phone = $("#phone").val();
        if (phone == "" || phone == "请输入11位手机号码" || phone == null) {
            NewAlertBox("warning", "请输入11位手机号码", 3000);
            return;
        }

        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if (!myreg.test($("#phone").val())) {
            NewAlertBox("warning", "请输入有效的手机号码!", 3000);
            $("#phone").val("");
            return;
        }

        var code = $("#code").val();
        if (code == "" || code == "请输入验证码" || code == null) {
            NewAlertBox("warning", "请输入验证码!", 3000);
            return;
        }

//        $.ajax({
//            url: "RelationCarNoByPhone.ashx?type=2&code=" + code + "&phone=" + phone,
//            type: "POST",
//            dataType: "json",
//            cache: false,
//            success: function (data) {


//                if (data.code == "0") {
                    NewAlertBox("warning", "绑定成功!", 3000, function () { WeixinJSBridge.call('closeWindow'); });
//                }
//                else {
//                    NewAlertBox("warning", data.msg, 3000, function () { WeixinJSBridge.call('closeWindow'); });
//                }
//            }
//        });

    }




    //获取验证码
    function getverify() {
        var phone = $("#phone").val();
        if (phone == "" || phone == "请输入11位手机号码" || phone == null) {
            NewAlertBox("warning", "请输入11位手机号码", 3000);
            return;
        }

        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if (!myreg.test($("#phone").val())) {
            NewAlertBox("warning", "请输入有效的手机号码!", 3000);
            $("#phone").val("");
            return;
        }


        timer(120);
//        $.ajax({
//            url: "RelationCarNoByPhone.ashx?type=1&phone=" + phone,
//            type: "POST",
//            dataType: "json",
//            cache: false,
//            success: function (data) {
//                if (data.code == "0") {
                    NewAlertBox("ok", "验证码获取成功!", 3000);
//                } else {
//                    NewAlertBox("warning", data.msg, 3000);
//                }
//            }
//        });


    }

</script>

从上面的代码中我们看到这个封装的js使用起来非常简单 NewAlertBox("warning", "请输入11位手机号码", 3000);传入一些参数就可以达到我们要的效果。

三.核心代码

我们要的效果也达到了,sAlter.js这个里面究竟是个什么样子的,其中代码如下:

/*
 js弹窗代码:用户体验极佳的Alert提示效果
 e-mail:616931@qq.com
 source:枫伶亿博客
*/
var t;
var argl,funcf;
//获取指定ID的元素
function $xp(id) {
 return document.getElementById(id);
}
//通用事件获取接口
function getEvent()
{
 if(CheckBrowser()=='IE')  return window.event;
 func=getEvent.caller;
 while(func!=null)
 {
  var arg0 = func.arguments[0];
  if(arg0)
  {
   if((arg0.constructor==Event || arg0.constructor ==MouseEvent)
   || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation))
   {
    return arg0;
   }
  }
  func=func.caller;
 }
 return null;
}
//alert
function NewAlertBox(itype,msg,time){//time为消失时间
 var msgbg,msgcolor,bordercolor,content,posLeft,posTop,imgName;
 argl=arguments.length;
 if(argl>3)
 {funcf = arguments[3];}//外部方法
 //弹出窗口设置
 msgbg = "#FFF";   //内容背景
 msgcolor = "#f66f15";  //内容颜色
 bordercolor = "#d8bfd8";  //边框颜色
 //遮罩背景设置
 //判断图片类型
 if(itype.toUpperCase()=='OK') //提示通过
     imgName = '../Img/ts_ok.png';
 else if(itype.toUpperCase()=='ERROR') //提示报错
     imgName = '../Img/ts_error.png';
 else //提示警告或者其他
     imgName = '../Img/ts_warning.png';
 
 content = "<img src='" + imgName + "' alt='img ' style='width:78px;height:78px;'/><br/>" + msg;
 var sWidth,sHeight;
 if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth)
    {
        sWidth = document.documentElement.clientWidth;
        sHeight = document.documentElement.clientHeight;
    }
    else
    {
        sWidth = screen.availWidth - 20;//防止溢出
         if(screen.availHeight > document.body.scrollHeight){
          sHeight = screen.availHeight; //少于一屏
         }else{
          sHeight = document.body.scrollHeight; //多于一屏
         }
    }
 //创建遮罩背景
 var maskObj = document.createElement("div");
 maskObj.setAttribute('id','maskdiv');
 //maskObj.setAttribute('onclick','CloseMsg()');
 maskObj.style.position = "absolute";
 maskObj.style.top = "0";
 maskObj.style.left = "0";
 maskObj.style.background = "#fff";
 maskObj.style.filter = "Alpha(opacity=40);";
 maskObj.style.opacity = "0.4";
 maskObj.style.width = sWidth + "px";
 maskObj.style.height = sHeight + "px";
 maskObj.style.zIndex = "10000";
 document.body.appendChild(maskObj);
 //创建弹出窗口
 var msgObj = document.createElement("div")
 msgObj.setAttribute("id","msgdiv");
 msgObj.setAttribute("onClick","CloseMsg()");
 msgObj.style.position ="absolute";
 sWidth = 230;
 sHeight = 180;
 msgObj.style.width = sWidth + "px";
 //msgObj.style.height = sHeight + "px";
 var event = getEvent();//申明event
 if(CheckBrowser()=='IE')
 {
  //posLeft = event.clientX + 10;  
  //posTop = event.clientY + document.documentElement.scrollTop;
  posLeft = (document.documentElement.clientWidth - sWidth) / 2 + "px";
  posTop = 50 + document.documentElement.scrollTop + "px";
  //posTop = (document.documentElement.clientHeight- sHeight) / 2 + "px";
 }
 else
 {
  //posLeft = event.pageX + 10 + "px";//ff下要申明px
  //posTop = event.pageY + 10 + "px";
  posLeft = (document.documentElement.clientWidth - sWidth) / 2 + "px";
  posTop = 50 + document.documentElement.scrollTop + "px";
  //posTop = (document.documentElement.clientHeight- sHeight) / 2 + "px";
 }
 msgObj.style.top = posTop;
 msgObj.style.left = posLeft;
 msgObj.style.fontSize = "18px";
 msgObj.style.background = msgbg;
 msgObj.style.border = "1px solid " + bordercolor;
 msgObj.style.zIndex = "10001";
 //创建内容
 var bodyObj = document.createElement("div");
 bodyObj.setAttribute("id","msgbody");
 bodyObj.style.padding = "10px";
 bodyObj.style.lineHeight = "1.5em";
 bodyObj.style.color = msgcolor;
 bodyObj.style.textAlign = "center";
 //var txt = document.createTextNode(content);
 //bodyObj.appendChild(txt);
 bodyObj.innerHTML = content;
 //生成窗口
 document.body.appendChild(msgObj);
 $xp("msgdiv").appendChild(bodyObj);
 if(time != '') t=setTimeout("CloseMsg()",time);
 else t=setTimeout("CloseMsg()",3000);//默认三秒后自动消失
 return false;
}
//移除对象
function CloseMsg(){
 $xp("msgdiv").removeChild($xp("msgbody"));
 document.body.removeChild($xp("msgdiv"));
 document.body.removeChild($xp("maskdiv"));  
 clearTimeout(t);//停止计时器
 t = null;
 if(argl>3)
 {funcf();}//执行外部传入的函数
}
//判断浏览器类型
function CheckBrowser(){
    var cb = "Unknown";
    if(window.ActiveXObject){
        cb = "IE";
    }else if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){
        cb = "Firefox";
    }else if((typeof document.implementation != "undefined") && (typeof document.implementation.createDocument != "undefined") && (typeof HTMLDocument != "undefined")){
        cb = "Mozilla";
    }else if(navigator.userAgent.toLowerCase().indexOf("opera") != -1){
        cb = "Opera";
    }
    return cb;
}

 四:项目代码打包下载

  点击下载程序源码

6楼Figgy
支持一下,用到的时候再来看……
Re: 枫伶忆
@Figgy,好基友一起来
5楼weeksun23
为何引入了jquery,还写那么多的原生JS代码?
Re: 枫伶忆
@weeksun23,Jquery是HTML页面引入的,sAlter.js这个插件并不是基于Jquery,要基于Jquery也可以,这个也是我在网上找过来的稍微修改下,你要是有兴趣可以改写下
4楼linkFly
目测就是专攻后端的。。。。。。。。。。,这个代码相对于前端来说真是不能直视。。。。。。,,鼓励鼓励,共勉共勉。
3楼南昌炒粉
挺好的,不过还有很长的路要走啊 唉
Re: 枫伶忆
@南昌炒粉,一起努力吧,js也是我一块心病
2楼进击的Jary
真不错。省下很多功夫呢。
Re: 枫伶忆
@进击的Jary,用的时候,直接拖这个js,就可以,而且手机端也可以用
1楼幻天芒
支持一下!
Re: 枫伶忆
@幻天芒,感谢