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>
幫助到你了,給小姐姐點贊喔~~😀