最近开发一个小项目,技术水平较低,然后弹框写的乱七八糟,之后想为啥不使用面向对象封装一下,每次调用不就ok了?然后就开始面向对象学习…
html:
<button id="btn1">按钮1</button>
<button id="btn2">按钮1</button>
css:
*{
margin: 0;padding: 0;text-decoration: none;list-style: none;
}
.clearfloat:after{content:'';display:block;clear:both;height:0;overflow:hidden;visibility:hidden;}
.clearfloat{zoom:1;}
.b_box{
position: absolute;
width: 100%;
height: 100%;
background: rgba(0,0,0,.7);
top: 0;
left: 0;
}
@media only screen and (min-width: 768px) {
.b_div{
width: 600px;
margin: 0 auto;
background: #fff;
border-radius: 5px;
animation: myopacity .5s forwards;
}
}
@media only screen and (max-width: 768px) {
.b_div{
width: 85%;
margin: 0 auto;
background: #fff;
border-radius: 5px;
animation: myopacity .5s forwards;
}
}
.b_div_active{
animation: myopacityover .5s forwards;
}
@keyframes myopacity{
from{
opacity: 0;
margin-top: 0;
}
to{
opacity: 1;
margin-top: 150px;
}
}
@keyframes myopacityover{
from{
opacity: 1;
margin-top: 150px;
}
to{
opacity: 0;
margin-top: 300px;
}
}
.b_div h3{
text-align: center;
font-size: 24px;
line-height: 60px;
}
.b_btn{
text-align: center;
padding: 10px 0;
margin-top: 10px;
}
.b_btn button{
border: none;
color: #FFFFFF;
padding: 5px 10px;
border-radius:3px;
margin: 0 10px;
}
.b_btn button:last-child{
background: #e01d1d;
}
.b_btn button:first-child{
background: #00a000;
}
.b_text{
text-align: center;
}
css写了媒体查询,看起来很多,真正关键的没多少
js:
var bouncesBox = document.createElement("div");
bouncesBox.setAttribute("class","bounces_box")
document.body.appendChild(bouncesBox)
function BInfo(title,txt){
this.title = title;
this.txt = txt;
this.info = function(){
var bouncesBox = document.getElementsByClassName("bounces_box")[0];
var _html = '<div class="b_box"><div class="b_div"><h3>'+this.title+'</h3><div class="b_text"><p>'+this.txt+'</p></div><div class="b_btn"><button class="b_info">确定</button></div></div></div>';
bouncesBox.innerHTML += _html;
this.divRemove()
};
}
BInfo.prototype.divRemove = function(){
var bInfo = document.getElementsByClassName("b_info")[0];
var bDiv = document.getElementsByClassName("b_div")[0];
bInfo.onclick=function(){
bDiv.classList.add("b_div_active");
bDiv.parentNode.remove()
}
}
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
btn1.onclick = function(){
var bInfo1 = new BInfo("提示信息","我是普通信息");
bInfo1.info()
}
btn2.onclick = function(){
var bInfo2 = new BInfo("提示信息2","我是普通信息2");
bInfo2.info()
}
说一下这个js:
BInfo()里面的this指向BInfo这个函数
BInfo.prototype.xxx:这个prototype是原型,这是一个指针,指向一个对象,大白话就是,BInfo.prototype.xxx和在BInfo里面写一个函数差不多,初期可以这样理解=.=
每次调用BInfo()这个函数的时候需要new BInfo();这样就可以重复调用,往里面写参数,就可以实现不同的弹框内容
说一下我踩到的坑:
我js开头的部分创建了一个div,BInfo里面创建的div是追加到这个创建的div中,然而,我一开始直接追加body里面的,但是这个btn的点击事件只能在页面刷新之后执行一次,再次点击失效,希望有明白人给我指点一下!!!
欢迎留言