標籤:
Android應用中的Toast主要是用於向使用者提示一些資訊,其用意與javascript中的alert()方法相同,但是美感卻比alert好,在輕應用中仿Android做出toast的效果更有原生App的體驗感。
目的:在html頁面產生仿Android的toast效果
語言:javascript+jQuery
方法聲明:
function toast(message, duration)
參數說明:
string message - toast提示內容
int duration - toast顯示期間(可選"long", "short"或具體毫秒數,"short"時為2000,"long"為5000,此參數不填時預設"short")
方法體:
var toast_id = 0; //外部變數,用來儲存setTimeout產生的計時器idvar zindex = 99; //這裡的z-index可以自己調整,保證在其他元素上不被遮擋function toast(message, duration) { window.clearTimeout(toast_id); //若短時間內調用兩次toast,清除上一次的timeout if (document.getElementById("app_toast")!=undefined) { //上次toast未消失,此時強制停止動畫並刪除該元素 $("#app_toast").stop(); document.body.removeChild(document.getElementById("app_toast")); } //設定逾時時間 duration = duration==null?"short":duration; if (duration=="short") duration = 2000; else if (duration=="long") duration = 5000; //定義新元素 var div = document.createElement("div"); div.setAttribute("style", "position:fixed;top:89%;text-align:center;width:95%;z-index:” + zindex);
div.setAttribute("id", "app_toast");
//寫入innerHTML內容,z-index為app_tpast的z-index值加1,value為提示內容 div.innerHTML = ‘<input type="button" id="app_txt_toast" style="padding-left:20px;padding-right:20px;border-radius:8px;opacity:0.2;height:20px;background:#000000;color:#ffffff;border:none;z-index:‘+(zindex+1)+‘;" value="‘+message+‘"/>‘; document.body.appendChild(div); //向document添加元素 $("#app_txt_toast").animate({height:‘29px‘,opacity:‘0.7‘}, 200, function(){}); $("#app_toast").animate({top:‘85%‘}, 200, function(){}); //製作一個toast從底部滑動效果 //持續duration毫秒後fadeout toast_id = window.setTimeout(function() { $("#app_toast").fadeOut(200, function() { document.body.removeChild(document.getElementById("app_toast")); toast_id = 0; }) }, duration);}
調用方法:toast("message")或toast("message", 3000)或toast("message", "short")
javascript+jQuery:仿Android Toast提示框