【发布时间】:2020-11-06 00:26:15
【问题描述】:
当我在 JavaScript 中触发函数时,我试图淡入 toast 消息。
我希望该函数创建元素,将其添加到 dom,然后使用 css 过渡淡入,然后使用相同的过渡淡出,然后将其从 dom 中删除。
淡出不会起作用,除非我将其包裹在超时中。
编辑 :: 里卡德
我添加了一个按钮来显示吐司。
function flashToast(msg, duration) {
duration = duration || 3000;
// create the toast element
const toastElement = document.createElement("p");
toastElement.innerHTML = msg;
toastElement.classList.add("toast");
// add it to the dom
document.body.appendChild(toastElement);
// fade in won't work unless I wrap it in a timeout
setTimeout(function() {
toastElement.style.opacity = "1";
}, 1);
// remove it after the duration is over
setTimeout(function() {
toastElement.style.opacity = "0";
}, duration - 500);
// start fading it out 500ms before removing it
setTimeout(function() {
document.body.removeChild(toastElement);
}, duration);
}
.toast {
display: inline-block;
font-size: 1.2rem;
padding: 0.8em 1em;
border-radius: 5rem;
color: #eaeaea;
background: #606060;
background: rgba(96, 96, 96, 0.7);
position: absolute;
bottom: 2%;
left: 50%;
transform: translate(-50%, -50%);
/* opacity is 0 when first enjected */
opacity: 0;
transition: opacity 500ms ease;
}
<button onclick="flashToast('Toast!')">Show toast</button>
【问题讨论】:
标签: javascript html css css-transitions