web-dev-qa-db-fra.com

Afficher une notification de pain grillé de style Android à l'aide de HTML/CSS/JavaScript

Normalement, lorsque vous souhaitez informer un utilisateur de quelque chose, vous utilisez une alerte. 

Maintenant, disons que je voudrais faire cela, mais de façon Android comme un toast, à savoir une fenêtre contextuelle qui apparaît à l'écran, mais quelques secondes plus tard, disparaît de lui-même pour que l'utilisateur ne soit pas dérangé en le fermant, comme sur l'image ci-dessous.

Comment une telle chose pourrait-elle être réalisée sur le Web?
Note: Faire une interface tactile donc c'est la raison pour laquelle je voudrais l'avoir de cette façon

enter image description here

35
anders

Le moyen le plus facile est de faire un titulaire où vous mettez votre message. Ce titulaire sera caché.

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

Vous ajoutez de la magie 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);
}

Ensuite, avec un script simple, vous pouvez l'afficher pendant quelques secondes. Utilisez .stop() si nécessaire 

$('.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

Ceci est un exemple très basique qui peut ensuite être transformé en une fonction avec des paramètres qui donneront le texte, la couleur, la durée et tout ce dont vous aurez besoin.

Ci-dessous, une manière plus avancée (inutilement compliquée) (un peu comme un plugin). Ici est aussi une version violon.

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

90
Spokey

Vous avez de bonnes bibliothèques sur Internet pour imiter le message de toast Android natif:

Fondamentalement est une div avec le message avec quelques CSS et une animation à afficher et masquer.

15
Jonathan Naguin

 enter image description here

Si vous voulez une notification comme celle-ci. Puis le code et les instructions sont ici (Excusez-moi koding.com :)))

Côté HTML (ajouter la fin du corps)

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

Côté 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}

Côté JS (bien sûr en utilisant la bibliothèque 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'});
}

Cas d'utilisation

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

Voici une solution CSS et Javascript simple. (Utilise Jquery, mais n'en a pas besoin). 

$("#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!"/> 

3
dwjohnston

Voici une bibliothèque Notify-js qui emprunte beaucoup à Toastr et la simplifie en quelque chose de similaire à Android-toast.

Il affiche une div avec quelques messages.

0
Morfat Mosoti