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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17723164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:50:30  来源:igfitidea点击:

Show an Android style toast notification using HTML/CSS/JavaScript

javascriptjqueryhtmlcss

提问by anders

Normally when you would like to make a user aware of something you use an alert.

通常,当您想让用户知道某些事情时,您会使用警报。

Now say I would like to do that but in a Android toastlike way, namely a popup that shows up on screen but then a few seconds later disappears by itselfso the user won't have to bother closing it, like the image below.

现在说我想这样做,但是以类似Android 吐司的方式,即显示在屏幕上的弹出窗口,但几秒钟后会自行消失,因此用户不必费心关闭它,如下图所示。

How could something like this be achieved in the web?
Note: Doing a touch interface so that's the reason I would like to have it in this way

如何在网络上实现这样的事情?
注意:做一个触摸界面,这就是我想以这种方式拥有它的原因

enter image description here

在此处输入图片说明

回答by Spokey

The easier way is to make a holder where you put your message. That holder will be hidden.

更简单的方法是在您放置信息的地方设置一个支架。该持有人将被隐藏。

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

You add some CSS magic

你添加了一些 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);
}

Then with a simple script you can show it for a few seconds. Use .stop()if necessary

然后使用一个简单的脚本,您可以将其显示几秒钟。.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 version

jsFiddle 版本

This is a very basic example that can then be changed into a function with parameters which will give the text, color, duration and anything else you may need.

这是一个非常基本的示例,然后可以将其更改为带有参数的函数,这些参数将提供文本、颜色、持续时间和您可能需要的任何其他内容。

Below a more advanced (unnecessarily complicated) way (kinda like a plugin). Hereis also a fiddle version.

下面是更高级(不必要地复杂)的方式(有点像插件)。这里也是一个小提琴版本。

(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>

回答by Jonathan Naguin

You have some good libraries on internet to mimic the native android toast message:

你在互联网上有一些很好的库来模仿原生的 android toast 消息:

Basically is a divwith the message with some CSS and an animation to show and hide.

基本上是一个div带有一些 CSS 和动画的消息来显示和隐藏。

回答by dwjohnston

Here's a simple CSS and Javascript solution. (Uses Jquery, but doesn't need to).

这是一个简单的 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!"/> 

回答by Musa

enter image description here

在此处输入图片说明

If you want notification like this. Then code and instruction is here (Excuse me koding.com :)))

如果你想要这样的通知。然后代码和说明在这里(对不起,koding.com :)))

HTML side (add end of body)

HTML 端(添加正文末尾)

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

CSS side

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 side (of course using jquery library)

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'});
}

Use case

用例

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

回答by Morfat Mosoti

Here is a Notify-jslibrary that borrows a lot from Toastrand simplifies it to something similar to android-toast.

这是一个Notify-js库,它从Toastr中借用了很多,并将其简化为类似于 android-toast 的东西。

It shows a divwith some messages in it.

它显示了div其中一些消息。