如何实现几秒钟后消失的警报

how to realize an alert that disappears after some seconds

我正在努力寻找一种方法来创建一个警报,当您单击一个按钮时它会打开,然后应该在可以设置为参数的时间后消失。

到目前为止我有这个:

<script>
function myFunction() {
    alert("I will think later what to write here");
}

</script>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $(".item_add").click(function(){
        myFunction();
    });
});
</script>

我应该如何修改代码才能达到这个结果?

谢谢大家的帮助!

您需要使用 HTML 个元素自行构建对话框。

完成此操作后,您应该检查 setTimeout() 允许您在预设时间段后执行功能 - 例如 visibility:hidden 您的自定义对话框。

var hideTimeout = 1000; //how many ms to wait before hiding after displaying

function customAlert() {

  //display the box
  var customAlert = document.getElementById("custom-alert-1");
  customAlert.style.visibility = 'visible';

  //set up a timer to hide it, a.k.a a setTimeout()
  setTimeout(function() {
    customAlert.style.visibility = 'hidden';
  }, hideTimeout)
}
body {
  text-align: center;
}
button {
  display: block;
  margin: 0 auto;
  margin-top: 32px;
}
.custom-alert {
  display: inline-block;
  visibility: hidden;
  background-color: #666;
  color: #fff;
  text-align: enter;
  margin: 5% auto;
  padding: 12px 48px;
}
<div id='custom-alert-1' class="custom-alert">Hello World</div>
<button onclick="customAlert()">Click to alert</button>

由于您使用的是 jQuery,因此您可以用 visibility 开关替换 $('#custom-alert-1').fadeOut(),从而提供更流畅的 show/hide 效果。


如果你说的是 'native' alert() 那么那将永远无法工作,因为除了打开它之外,JS 无法以任何方式访问它