先看效果图:
废话不多说,直接上代码
index.html
function func666(alert_id){
alert(666);
removeAlertBox(alert_id);
}
function func777(alert_id){
alert(777);
removeAlertBox(alert_id);
}
用法非常简单,只要在script模块中调用:alertWithOk('带确定框');
alertNoOk('不带确定框,且自动消失');
myAlert.jsvar arr_alert_okFunc = {};
var arr_alert_cancelFunc = {};
var alert_id = 0;
function removeAlertBox(alert_id){
document.getElementById('mask_box' + alert_id).remove();
}
function alert_okFunc(alert_id){
var func = arr_alert_okFunc[alert_id];
if(!func){
removeAlertBox(alert_id);
return;
}
func(alert_id);
}
function alert_cancelFunc(alert_id){
var func = arr_alert_cancelFunc[alert_id];
if(!func){
removeAlertBox(alert_id);
return;
}
func(alert_id);
}
function createAlertBox(content, okFunc, noFunc, okText, cancelText, disappearTime, noOk){
alert_id++;
var id_mask_box = 'mask_box' + alert_id;
var div = document.createElement('div');
div.setAttribute('id', id_mask_box);
var container = document.getElementsByTagName("body")[0];
container.insertBefore(div,container.childNodes[0]);
var closeSelf = function(id){
document.getElementById('mask_box' + id).remove();
};
if(!okText){
okText = '确定';
}
if(!cancelText){
cancelText = '取消';
}
if(okFunc){
arr_alert_okFunc[alert_id] = okFunc;
}
if(noFunc){
arr_alert_cancelFunc[alert_id] = noFunc;
}
var mask_bottomStyle = '';
if(noOk == 1){
mask_bottomStyle += 'style = "display:none;"';
}
if(disappearTime){
setTimeout(function(){closeSelf(alert_id)}, disappearTime);
}
div.innerHTML =
'
'
'
'
'
'' + cancelText + ' ' +
'' + okText + '' +
'
'
'
}
function alertWithOk(content, okFunc, noFunc, okText, cancelText){
createAlertBox(content, okFunc, noFunc, okText, cancelText);
}
function alertNoOk(content, okFunc, noFunc, okText, cancelText, disappearTime){
if(!disappearTime){
disappearTime = 1200;
}
createAlertBox(content, okFunc, noFunc, okText, cancelText, disappearTime, 1);
}
myAlert.css.mask_back{
position: fixed;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
}
/*弹出层*/
.mask_center{
width: 95%;
max-width: 500px;
max-height: 230px;
margin: auto;
margin-top: 5%;
text-align: center;
background-color: #fff;
border: 1px solid #999;
border-radius: 6px;
}
.mask_bottom{
padding: 19px 20px 20px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.mask_content{
padding: 20px 5px;
}
.mask_bottom a{
cursor: pointer;
border: 1px solid #aaa;
padding: 6px 12px;
font-size: 14px;
border-radius: 4px;
color: #000;
background-color: #fff;
text-decoration: none;
}
.mask_bottom a:hover{
background-color: #428bca;
color: #fff;
}
.mask_close{
float: right;
font-size: 18px;
font-weight: 700;
color: #aaa;
text-shadow: 0 1px 0 #fff;
cursor: pointer;
margin-right: 10px;
}
带确定框效果如下: