您的位置:首页 > 移动开发

移动端使用js出轻量级吐司提示

2016-04-27 16:27 337 查看
/**
* 自定义吐司 littlehow 2015-12-10
*/
var toast = {
c:function(tag){
return document.createElement(tag);// 创建标签
},
bgColor:"#59B9C6",
color:"white",
fontSize:45,
initFlag:false, //初始化
toast:null,
td:null,
showTime:1500,
showFlag:false,
timeoutKey:null,
widthPercent:0.8, //宽度占用比例为80%
local:{x:0, y:0, width:540, height:120},
tableHeight:120,
contentTable:null,
pagePercent:0.6,
radius:50,
top:999999,
init:function(){
var p = this.c("div");
var ww = document.body.clientWidth;//获取屏幕宽度
if(ww>0){
this.local.width = Math.ceil( ww * this.widthPercent );
}
//设置样式
p.style.width = this.local.width + "px";
p.style.position = "absolute";
p.style.zIndex = this.top; //置于顶层
p.style.textAlign = "center";
p.style.verticalAlign = "middle";
p.style.backgroundColor = this.bgColor;  // 灰色背景
//p.style.opacity = 0.8;
p.style.borderRadius = this.radius + "px";
this.toast = p;
this.initFlag = true;
// 设置内容
this.initContent();
},
setPercent:function(percent){
var increase = percent / this.pagePercent;
var fontSize = Math.ceil(this.fontSize / increase);
this.local.height = Math.ceil(this.tableHeight / increase);
this.toast.style.height = this.local.height + "px";
this.td.style.fontSize = fontSize + "px";
this.contentTable.style.height = this.local.height + "px";
},
initContent:function(){
var t = this.c("table");
t.style.width = this.local.width + "px";
t.style.height = this.local.height + "px";
t.align = "center";
var b = this.c("tbody");
var tr = this.c("tr");
this.td = this.c("td");
this.td.style.textAlign = "center";
this.td.style.verticalAlign = "middle";
this.td.style.color = this.color;
tr.appendChild(this.td);
b.appendChild(tr);
t.appendChild(b);
this.toast.appendChild(t);
this.contentTable = t;
},
initLocation:function(){
var scrollTop = document.body.scrollTop;   // 当前滚动条的竖直滚动位置
var scrollLeft = document.body.scrollLeft;  // 当前滚动条的水平滚动位置
var width = document.body.clientWidth;  // 当前屏幕的宽度
var height = document.body.clientHeight;  // 当前屏幕的高度
// 计算居中位置
this.local.x = Math.ceil((width - this.local.width)/2) + scrollLeft;
this.local.y = Math.ceil((height - this.local.height)/2) + scrollTop;
},
show:function(value, percent){
if(!this.initFlag){
this.init();
}
//设置比例
if(typeof percent==="number") {
this.setPercent(percent);
}else{
this.setPercent(this.pagePercent);
}
//初始化当前位置
this.initLocation();
this.toast.style.left = this.local.x + "px";
this.toast.style.top = this.local.y + "px";
this.toast.style.zIndex = this.top;
this.td.innerHTML = value;
// 判断当前是否早show
if(this.showFlag){
window.clearTimeout(this.timeoutKey);
}else{
document.body.appendChild(this.toast);
}
this.timeoutKey = window.setTimeout(this.hidden, this.showTime);
this.showFlag = true;
},
hidden:function(){
var me = MGSD.utils.toast;
if(me.initFlag){
window.clearTimeout(me.timeoutKey);// 不管如何消失, 都执行取消定时消失
me.td.innerHTML = "";
document.body.removeChild(me.toast);
me.showFlag = false;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: