下記JavaScriptを定義した上で, showToast("hogehoge", 5);
とすれば, 5秒間だけトーストスタイルで"hogehoge"が表示される
Toast.js
////
//// Show Toast Style Message From JavaScript.
///////////////////////////////////////////////////////////////////////////////////////
var timer;
var toastElement;
///
/// Method For Show Toast Style Message
/// @param message Meesage String
/// @param second Second For Message Showing. Or Default Setting Time(=3second)
///
function showToast( message, second ) {
second = second || 3;
var divElement = document.createElement("div");
var spanElement = document.createElement("span");
setToastStyle(divElement, spanElement);
spanElement.innerText = message;
divElement.appendChild(spanElement);
document.body.appendChild(divElement);
// Adjust Message Show Place
divElement.style.position = "absolute";
divElement.style.left = (window.innerWidth/2 - divElement.offsetWidth/2) + "px";
divElement.style.top = (window.innerHeight*3/4) + "px";
toastElement = divElement;
var from = 0;
var distance = 0.8;
var duration = 1000;
var begin = new Date() - 0;
var id = setInterval(function() {
var time = new Date() - begin;
var current = easing(time, from, distance, duration);
if( time > duration ) {
clearInterval(id);
current = from + distance;
// Remove Toast From Display
timer = setTimeout("removeToast()", second * 1000);
} else {
toastElement.style.opacity = current;
toastElement.style.transparent = current;
}
}, 10);
}
///
/// Style Setting For Toast Style Message.
///
function setToastStyle(divElement, spanElement) {
divElement.style.padding = "10px 70px";
spanElement.style.padding = "3px";
divElement.style.backgroundColor = "#f0e68c";
divElement.style.borderRadius = "1em";
divElement.style.border = "1px solid red";
divElement.style.opacity = 0;
divElement.style.transparent = 0;
}
///
/// Remove Toast From Display
///
function removeToast() {
if( toastElement ) {
var from = 0.8;
var distance = -0.8;
var duration = 1000;
var begin = new Date() - 0;
var id = setInterval(function() {
var time = new Date() - begin;
var current = easing(time, from, distance, duration);
if( time > duration ) {
clearInterval(id);
current = from + distance;
document.body.removeChild(toastElement);
toastElement = null;
} else {
toastElement.style.opacity = current;
toastElement.style.transparent = current;
}
}, 100);
}
}
function easing( time, from, distance, duration ) {
return distance * time / duration + from;
}