以下是一个用js实现的toast提示框的示例,包括css和html元素:

HTML:

<div class="toast-container">
  <div class="toast-message"></div>
</div>

CSS:

.toast-container {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
}

.toast-message {
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 5px;
  text-align: center;
  max-width: 90%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: none;
}

JS:

function showToast(message, duration) {
  var toastContainer = document.querySelector('.toast-container');
  var toastMessage = document.querySelector('.toast-message');
  toastMessage.innerHTML = message;
  toastContainer.style.display = 'block';
  toastMessage.style.display = 'block';
  setTimeout(function() {
    toastContainer.style.display = 'none';
    toastMessage.style.display = 'none';
  }, duration);
}

// 示例用法
showToast('这是一个toast提示框', 3000);

说明:

  1. showToast 函数接受两个参数:提示内容和显示时长(毫秒)。
  2. 在函数内部先获取到 .toast-container.toast-message 这两个元素。
  3. 将提示内容设置为 .toast-message 的 innerHTML,并将 .toast-container.toast-message 的 display 属性设置为 block,显示出提示框。
  4. 使用 setTimeout 函数在指定时间后将 .toast-container.toast-message 的 display 属性设置为 none,隐藏提示框。
  5. 示例用法中传入了一个显示时长为 3000 毫秒的参数,可以根据实际需要进行调整。
用js生成一个 toast 提示框全部用js实现 包括css和html元素

原文地址: http://www.cveoy.top/t/topic/bgf2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录