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

原生js实现自定义alert风格和实现

2018-03-25 11:04 489 查看

2018年6月29 最新更新

添加函数节流,解决多次点击问题,添加单例模式,提高代码性能。

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>自定义alert</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no" name="viewport" />
<style type="text/css">
html,
body {
padding: 0;
margin: 0;
}
/*     //防止鼠标双击选中文字
*/

div {

-khtml-user-select: none;
/*早期浏览器*/
user-select: none;
}
/*  //来自animated.css的样式 */

@-webkit-keyframes fadeIn {
0% {
opacity: .7
}
50% {
opacity: 1
}
100% {
opacity: .7
}
}

.toast {
-webkit-animation-name: fadeIn;
-webkit-animation-duration: 3s;
-webkit-animation-iteration-count: 1;
-webkit-animation-delay: 0s;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
transition: all .3s ease;
max-width: 80%;
color:#fff;
background: #2B2B2B;
padding: 8px 15px;
display: inline-table;
border-radius: 3px;
}

.toast-ui {
position: fixed;
top:20%;
color:#fff;
width: 100%;
text-align: center;
}

.maskfadeout {
display: block;
-webkit-animation: fadeout 3s linear;
animation: fadeout 3s linear;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1
}

@-webkit-keyframes fadeout {
0%,
80% {
opacity: 1
}
100% {
opacity: 0
}
}

@keyframes fadeout {
0%,
80% {
opacity: 1
}
100% {
opacity: 0
}
}
</style>
</head>

<body>
<script type="text/javascript">
(function(win, doc) {
var alert = function(text, time, top) {
text = text || "确定删除?", time = time || 3000, top = top || "10%"; //增加默认值,增强健壮性
var body = doc.getElementsByTagName("body")[0]; //优化dom
//实现alert
var div = doc.createElement("div");
div.className = "toast-ui maskfadeout";
div.id = "alert";
var span = doc.createElement("span");
span.innerHTML = text;
span.className = "toast";
div.appendChild(span);
body.appendChild(div);

setTimeout(function() {
div.style.display="none";
}, 3000);
}
win.alert = alert; //导出
})(window, document);
alert("是否删除这条评论?");
</script>
</body>

</html>
View Code

本文结束。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: