最近看javascript的面向对象开发,试着写了一个弹窗,基于jquery

用的组合模式,也是用的最广泛的,在构造函数中定义属性和方法,在原型中添加方法。

弹窗最基本的属性也就是宽和高了,这里我把弹窗的HTML的代码也写进了一个属性,方便直接使用,还有弹窗的ID方便创建多个窗体。

一、【构造函数】

function JqWindow(WindowID,WindowWidth,WindowHeight){
    //窗口宽 给了默认值300
    this.width=(typeof(WindowWidth)=='undefined')?300:parseInt(WindowWidth,10);
    //窗口高 给了默认值300
    this.height=(typeof(WindowHeight)=='undefined')?300:parseInt(WindowHeight,10);
    
    //窗口的ID属性
    this.winID=WindowID;
    
    //弹窗的HTML
    var reval;
    reval  = "";
    reval += "<div id=\""+this.winID+"\" class='TB_Window'>";
    reval += "    <div class=\"TB_Head\">";
    reval += "        <div class=\"TB_WindowTitle\"></div>";
    reval += "        <div class=\"TB_close\"><a href=\"javascript:;\">×</a></div>";
    reval += "    </div>";
    reval += "    <div class=\"TB_Content\">";
    reval += "        ";
    reval += "    </div>";
    reval += "</div>";
    this.windowHtml=reval;
    
}

 

二、【初始化】将窗口初始化方法在原型中添加

//初始化
JqWindow.prototype.init=function(event){    
    //判断页面中是否有此窗口
    if($("#"+this.winID).length==0)
    {    
        //没有 在body中加入并设为透明
        $("body").append(this.windowHtml);    
        $("#"+this.winID).css({opacity:0});
    }
    
    //弹窗已显示后 不再重新初始化样式
    if($("#"+this.winID).css("opacity")!=1)
    {
        //获取鼠标点击时的位置 将窗口显示在该位置
        var mouseX=event.pageX;
        var mouseY=event.pageY;
        $("#"+this.winID).show().css({left:mouseX,top:mouseY});
    }

    
}

 

三、【显示弹窗】

//show方法  显示弹窗
JqWindow.prototype.show=function(event){
    //初始化
    this.init(event);
    
    //取网页中心点
    var middleWidth=parseInt($("body").width(),10)/2;
    var middleHeight=parseInt($("body").height(),10)/2;
    var W_marginLeft=-this.width/2;
    var W_MarginTop=-this.height/2;
    
    //弹窗出现的动画
    $("#"+this.winID).animate({left:middleWidth,top:middleHeight,marginLeft:W_marginLeft,marginTop:W_MarginTop,width:this.width,height:this.height,opacity:1});
}

 

四、【关闭弹窗】

//hide方法 关闭弹窗
JqWindow.prototype.hide=function(event){
    //获取鼠标位置
    var mouseX=event.pageX;
    var mouseY=event.pageY;
    
    //弹窗关闭动画
    $("#"+this.winID).animate({left:mouseX,top:mouseY,opacity:0,width:0,height:0},function(){
        //在IE6中关闭后会显示一个点,opacity透明度兼容有一定问题,所以最后还是隐藏
        $("#"+this.winID).hide();
    });
}

 

五、【页面中使用】

var TB=new JqWindow("jqWin",300,200);
//点击按钮 出现弹窗
$("#Bt").click(function(event){
    TB.show(event);    
})

//点击关闭按钮 关闭弹窗
$("#close").click(function(event){
    TB.hide(event);    
})

 

自己动手也算是加强记忆把,光看书也不一定会用,还是要多实践,哪怕是最简单的,为以后的复杂打好基础!

posted @ 2012-07-23 14:18  BiakeChou  阅读(450)  评论(0编辑  收藏  举报