js 封装弹出层简单方法

1.js代码

function Tanshow(){
     

}
Tanshow.prototype.$alert=function(title,content){
       //弹出方法   (传行参)
    var divDom=document.createElement("div")  //创建div节点
    divDom.setAttribute("id","tan")   //给div设置id

    var h1Dom=document.createElement("h1")   //创建h1节点
    h1Dom.setAttribute("id","title")     //给h1设置id
    h1Dom.innerHTML=title;     //h1里面添加title参数

    var contentDom=document.createElement("p")  //创建p节点
    contentDom.setAttribute("id","content");   //给p设置id
    contentDom.innerHTML=content;      //p里面添加content参数

    divDom.append(h1Dom)   //div末尾添加h1
    divDom.append(contentDom)   //div末尾添加p


    var styles={
               //弹出层的基本css样式
        "display":"block",
        "position": "absolute",
        "top": 0,
       	"bottom": 0,
        "left": 0,
        "right": 0,
        "margin": "auto",
        "width": "200px",
        "height": "200px",
        "background": "rgba(0, 0, 0, 0.6)",
        "text-align": "center",
    }
    for( let key in styles ){
         
        divDom.style[key]=styles[key]    //循环 给div添加style属性=styles的值
    }
    document.body.append(divDom)   //把div添加到body末尾
}

Tanshow.prototype.$hide=function(){
        //关闭方法
    document.body.removeChild(document.getElementById("tan"))   //删除body的子节点
}

var tool=new Tanshow()  //实例化Tanshow

2.html页面部分( 记得载入封装好的js文件 )

<script src="./1.js"></script>
<body>
    <button onclick="tan()">弹出</button>
    <button onclick="closes()">关闭</button>

    <script>
        function tan(){
     
            tool.$alert("hello","hi")
        }
        function closes(){
     
            tool.$hide();
        }
    </script> 

帮助到你了,给小姐姐点赞喔~~

你可能感兴趣的:(js,javascript,html,css)