如何使用JavaScript应用到click toast

问题描述 投票:0回答:1

我遇到了一个与 JavaScript 相关的问题,如何应用 toast。

我需要使用 JavaScript 应用点击 toast 的帮助,但是只有当给定条件不为真时,toast 才必须出现,如果给定条件为真,则页面将在没有该 toast 的情况下工作。

javascript html bootstrap-4
1个回答
0
投票

您可以使用条件语句和 DOM 操作的组合来检查此示例代码,您可以根据您的设计进行更改。您可以使用 javascript 插件,例如 toastrjs,carlosroso.com/notyf/

function showToast(message) {
      // Create a toast div element
      const toast = document.createElement('div');
      toast.classList.add('toast');
      toast.innerText = message;
    
      // Append the toast to the body
      document.body.appendChild(toast);
    
      // Set a timeout to remove the toast after a certain period
      setTimeout(() => {
        toast.remove();
      }, 3000); // Toast will be automatically removed after 3 seconds
    }
    
    function handleClick() {
      // Your condition
      const condition = false;
      
      if (!condition) {
        // Call the showToast function with the desired message
        showToast('Oops, something went wrong!');
      }
    
      // Rest of your click event logic goes here
      // ...
    }
    
    // Attach the handleClick function to your button's click event
    const button = document.getElementById('your-button-id');
    button.addEventListener('click', handleClick);

我希望这能解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.