您的位置:首页 > Web前端 > JavaScript

自定义实现js的confirm方法

2016-08-11 00:00 337 查看
摘要: js自带的alert方法和confirm方法采用了阻塞线程的实现方式来100%防止代码被继续运行,直到用户做出响应,但是当自己编写confirm方法是就没有,所以要实现confirm的自定义就必须先解决阻塞线程的问题,在此,通过传参数实现阻塞效果。代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style type="text/css">
/*水平垂直都居中*/
.ctmd{
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
-webkit-box-align: center;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: center;
-moz-box-align: center;
display: -o-box;
-o-box-orient: horizontal;
-o-box-pack: center;
-o-box-align: center;
display: -ms-box;
-ms-box-orient: horizontal;
-ms-box-pack: center;
-ms-box-align: center;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
/*弹出信息*/
#confirm{
display:block;
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background: rgba(255,255,255,0.4);
z-index: 100;
}
#confirm .confirmdiv{
width:100%;
height: 100%;
}
#confirm .confirms{
border-radius: 5px;
/* color: #fff;
width: 200px;*/
padding: 10px;
/* height: 100px; */
background: rgba(19, 48, 78,0.8);
border: 1px solid rgba(19, 48, 78 ,0.8);
}
#confirm .confirms p{
text-align:center;
color:#fff;
font-size: 1.8rem;
}
#confirm .confirms p button.sure{
background: #69B169;
padding: 8px 12px;
margin-left: 2rem;
}
#confirm .confirms p button.sure:hover{
background: #49AD49;
color:#fff;
}
#confirm .confirms p button.not{
padding: 8px 12px;
color:#626262;
}
#confirm .confirms p button.not:hover{
background: #ccc;
color:#626262;
}
</style>
</head>
<body>
<div class="div2 border">
<div class="div1">
<div class="div3">
<button class="btn" onclick="Romover()">点击</button>
</div>
</div>
</div>
<div class="div1 border">
</div>
<script src="common/js/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
/*删除产品*/
function Romover(){
var r=confirm("您确定要删除吗?", function(){
alert("你点了确定");
}, function(){
alert("你点了取消");
});
}
/*页面弹出的提示信息*/
function confirm(test,okCallback, cancleCallback){
if(document.getElementById('confirm')) return false;
var div = document.createElement('div');
div.id = 'confirm';
div.innerHTML = '<div class="confirmdiv ctmd"><div class="confirms"><p>'+test+'</p>'+
'<p><button class="btn not pull-left">取消</button>'+
'<button class="btn sure pull-right">确认</button></p></div></div>';
document.body.appendChild(div);
$("body #confirm button.sure").on('click',function(){
document.getElementById('confirm') && document.body.removeChild(document.getElementById('confirm'));
console.log("msg=true");
okCallback();
});
$("body #confirm button.not").on('click',function(){
document.getElementById('confirm') && document.body.removeChild(document.getElementById('confirm'));
console.log("msg=false");
cancleCallback();
});
}
</script>
</body>
</html>

在confirm(test,okCallback, cancleCallback)方法中,okCallback函数为点击确认后执行的函数,cancleCallback函数为点击取消后执行的函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息