- 简单H5提示消息封装
前言
前几天在写H5的时候,感觉很多原生的东西都要去一点一点去写很麻烦,就想着自己封装一些常用的组件,作为自己的组件库,记录自己的成长点滴。
H5消息提示弹框
废话不多说代码如下:
/*
*消息弹框
* @ var message = new $message()
* @ message(options,newclass)
* @ options Object||string {message:'message',time:2000} || 'message'
* @ newclass string class类名
*/
function $message() {
this.time = 2000;
this.timer = null;
this.newDiv = null;
this.message = "";
this.fn = function(options, newclass) {
if (typeof options === 'string') {
this.message = options;
this.time = 2000;
} else if (typeof options === 'object') {
this.time = options.time || 2000;
this.message = options.message;
} else {
return
}
this.newDiv = document.createElement("div")
this.newDiv.className = "message"
this.newDiv.className += newclass || "";
//自定义样式 可以注释掉行间样式
this.newDiv.style =
'position:absolute;left: 50%;top: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);background-color: rgba(0, 0, 0, 0.8);color: #fff;padding: .6rem;font-size: 1rem;border-radius: .4rem;text-align: center;zIndex:2250';
document.body.appendChild(this.newDiv);
this.newDiv.innerHTML = this.message;
this.closes = function() {
console.log(this)
this.newDiv.parentNode.removeChild(this.newDiv);
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(this.closes.bind(this), this.time);
}
return this.fn.bind(this);
}
var message = new $message()
var msg = document.querySelector("#msg")
msg.onclick = () => {
message("这是提示框", )
}
欢迎各位大佬提出需要改进和不足的地方!