使用HTML/CSS/JavaScript显示类似Android风格的Toast通知

40

通常,当您想让用户了解某些事情时,您会使用弹出框(alert)。

现在假设我想以类似于Android toast(安卓提示)的方式来做这件事,也就是出现在屏幕上但几秒钟后自动消失,所以用户不必费心去关闭它,如下图所示。

在Web中,如何实现类似这样的功能?
注意:我们将使用触摸接口,这就是我想以这种方式完成的原因。

图片描述


一个 jQuery toastmessage 插件就可以了。 - Tanveer Shaikh
6个回答

96

更简单的方式是创建一个放置您的信息的容器。该容器将被隐藏。

<div class='error' style='display:none'>Event Created</div>

你添加了一些 CSS 魔法

.error {
    width:200px;
    height:20px;
    height:auto;
    position:absolute;
    left:50%;
    margin-left:-100px;
    bottom:10px;
    background-color: #383838;
    color: #F0F0F0;
    font-family: Calibri;
    font-size: 20px;
    padding:10px;
    text-align:center;
    border-radius: 2px;
    -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
}

然后,通过一个简单的脚本,您可以将其显示几秒钟。如有必要,使用.stop()

$('.error').fadeIn(400).delay(3000).fadeOut(400); //fade out after 3 seconds

$('button').click(function () {
    $('.error').text($(this).data('text')).fadeIn(400).delay(3000).fadeOut(400); 
});
body, html {
    height:100%;
    width:100%;
    min-height:100%;
    padding:0;
    margin:0;
}
.error {
    width:200px;
    height:20px;
    height:auto;
    position:absolute;
    left:50%;
    margin-left:-100px;
    bottom:10px;
    background-color: #383838;
    color: #F0F0F0;
    font-family: Calibri;
    font-size: 20px;
    padding:10px;
    text-align:center;
    border-radius: 2px;
    -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
    box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class='error' style='display:none'></div>
<button data-text='I did something!'>Do something!</button>

jsFiddle版本

这是一个非常基本的例子,可以改变参数并使其成为具有文本、颜色、持续时间和其他任何需要的功能。

下面是一种更高级(不必要复杂)的方式(有点像插件)。这里也提供了 fiddle 版本。

(function($) {
  $.fn.aToast = function(options) {

    var $this = $(this),
      settings = $.extend({
        fadeOut: 400,
        fadeIn: 400,
        delay: 3000,
        text: 'Whoops! Something happened and I showed up.',
        toastListenEvent: 'click',
        aClass: false
      }, options),
      $at = false,
      aTevents = false;

    settings.toastListenEvent = settings.toastListenEvent + ' a-Toast';
    settings.aClass = 'aToast-view-message' 
                  + (settings.aClass ? ' ' + settings.aClass : '')
    if ($('[data-aToast=true]:not(.aToast-init)').length) 
      $this = $this.add($('[data-aToast=true]:not(.aToast-init)')
                                       .addClass('aToast-init'));

    function _remove() {
      $(this).stop().remove();
    }

    function _displayDiv() {
      $('.aToast-view-message').hide();
      var da = $(this).data('atoast-text');
      var $div = $('<div/>', {
          text: da ? da : settings.text,
          class: settings.aClass
        }).stop().fadeIn(settings.fadeIn)
        .delay(settings.delay)
        .fadeOut(settings.fadeOut, _remove)
        .appendTo('body');
    }

    $this.not('[data-aToast=false]').on(settings.toastListenEvent, _displayDiv);

  };
}(jQuery));

$('button').aToast({
  aClass: 'users-dont-care-about-this-class-name'
});

$('div').aToast({
  aClass: 'hehe',
  toastListenEvent: 'mouseenter',
  text: 'Okay, this is not working'
});


/* or 

$().aToast({
    aClass: 'users-dont-care-about-this-class-name'
});

To listen to data-aToast only

*/
body,
html {
  height: 100%;
  width: 100%;
  min-height: 100%;
  padding: 0;
  margin: 0;
}
.aToast-view-message {
  width: 200px;
  height: 20px;
  height: auto;
  position: absolute;
  left: 50%;
  margin-left: -100px;
  bottom: 10px;
  background-color: #383838;
  color: #F0F0F0;
  font-family: Calibri;
  font-size: 20px;
  padding: 10px;
  text-align: center;
  border-radius: 2px;
  -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
  -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
  box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1);
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Here goes nothing</button>
<input type='button' data-aToast='true' data-aToast-text='Hey there.' value='Woop!' />
<div style='display:inline-block'>I am a div! Hover me</div>


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Sameer Alibhai
嗨@Spokey..我在Chrome中尝试了这个,但它出现了错误“Uncaught TypeError: myDiv.stop不是一个函数”。 - SurajS
没有 "stop()",它会在多次点击时继续执行相同的操作。 - SurajS
嘿@SurajS,你能在fiddle中展示一个例子吗?.stop()只会停止动画并在触发时从头开始运行。我认为你可能正在寻找一种禁用该操作的方法? - Spokey
抱歉..这是语法问题..当所有函数都开始出现相同的错误时,我才知道发生了什么..感谢您的回复 :) - SurajS
显示剩余3条评论

15

谢谢回复,我会研究一下,但最好还是自己动手做,因为你说这并不像我想象的那么难。 :) - anders
https://github.com/jadjoubran/Android-Toast 很容易上手 - 只需从GitHub复制/包含2个文件,然后1行代码即可显示toast。谢谢 - Gene Bo

6
这是一个简单的CSS和Javascript解决方案。(使用Jquery,但并不需要) 。

$("#clickme").click(function() {
      $("body").append("<span class ='toast'>Hello World!</span>");

      setTimeout(function(){
        $(".toast").remove();
      },3000);
}); 
.toast {
  position: fixed;
  display:block;

  bottom: 2em;
  height: 2em;
  width: 10em;
  left: calc(50% - 5em);

  animation: toast-fade-in 1s 2 alternate;


  background-color: black;
  border-radius: 2em;

  color: white;
  text-align: center;
  padding: 1em;
  line-height: 2em;

  opacity: 0;

}


@keyframes toast-fade-in {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "clickme" type = "button" value = "click me!"/> 


太棒了。 - Sandeep Londhe

5

在此输入图片描述

如果您想要这样的通知,那么代码和说明在这里(对不起koding.com :))))

HTML侧(在body末尾添加)

<div id="notification" class="kdnotification main">
  <div class="kdnotification-title"></div>
</div>

CSS 侧边栏
.kdnotification{display:none}
.kdnotification a{text-shadow:0 1px 0 #444}
.kdnotification{position:fixed;padding:10px;z-index:20001;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}
.kdnotification .kdnotification-title{color:#fff;font-size:24px;line-height:36px;margin:2px;font-weight:700}
.kdnotification .kdnotification-content{font-size:16px;line-height:18px;color:#fff}
.kdnotification .kdnotification-timer{position:absolute;top:21px;right:25px;color:#fff;line-height:15px;text-align:center;font-size:15px;width:20px;height:24px}
.kdnotification a{position:absolute;cursor:pointer;display:block;top:24px;right:5px;line-height:24px;text-align:center;font-size:24px;text-decoration:none;color:#fff;width:20px;height:24px}
.kdnotification-title{font-size:18px;line-height:28px;float:none}
.kdnotification-title{font-size:12px;line-height:16px;font-weight:400;float:none}
.kdnotification.mini{-webkit-border-radius:0 0 5px 5px;-moz-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;padding:1px;-webkit-box-shadow:0 0 1px 1px rgba(255,255,255,.1),inset 0 0 2px #000;-moz-box-shadow:0 0 1px 1px rgba(255,255,255,.1),inset 0 0 2px #000;box-shadow:0 0 1px 1px rgba(255,255,255,.1),inset 0 0 2px #000}
.kdnotification-title{font-size:12px;line-height:16px;font-weight:400;float:none;padding:2px 10px}
.kdnotification.mini .kdnotification-title p{padding:0 10px}
.kdnotification.mini.error{background:rgba(185,74,72,.9);font-weight:600}
.kdnotification.mini.success{background:rgba(70,136,71,.8);font-weight:600}

JS端(当然需要使用jquery库)

function notify(message,status){
  $('.kdnotification-title').html(message);
  funcking();
  if(status == 1){
    $('#notification').css({'background-color':'rgba(0,0,0,.4)'}).fadeIn('slow').delay(5000).fadeOut('slow');
  } else {
    $('#notification').css({'background-color':'rgba(216,0,12,.6)'}).fadeIn('slow').delay(3000).fadeOut('slow');
  }
}

function funcking(){
    var kd=$('.kdnotification');
    var viewportHeight = $(window).height(),
        viewportWidth = $(window).width(),
        kdheight = kd.height(),kdwidth = kd.width(),
        hdiff = viewportHeight - kdheight,
        vdiff = viewportWidth - kdwidth,
        left= vdiff/2,
        top = hdiff/2;
    kd.css({'top':top+'px','left':left+'px'});
}

使用场景

if(success){
  notify("Success message",1);
} else {
  notify("Error message",0);
}

0
这里有一个Notify-js库,它借鉴了很多Toastr的思路,并将其简化为类似于Android-toast的形式。
它会显示一个带有一些消息的div

0

我建议您使用这个轻量且简单的 ToastMaker 库,它完全符合 Android toast 的外观和感觉,并且只有 1KB 大小。

$('#mybutton').click(()=>{ToastMaker("This is a toast notification!")});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://unpkg.com/toastmaker/dist/toastmaker.min.css">

<script type="text/javascript" src="https://unpkg.com/toastmaker/dist/toastmaker.min.js"></script>


<button id="mybutton">Show Toast</button>

访问此页面以查看更多具有美丽样式的提示消息示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接