Greasy Fork

Notify Library

Very Simple JS Notifications Library

目前为 2020-04-21 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.icu/scripts/401626/795716/Notify%20Library.js

/* **************

  Notify Library 1.1.2
  Developed by pizidavi

  Options:
    - text    required
    - type    optional
      - success
      - info/information
      - warn/warning
      - error
    - delay   optional

************** */

var Notify = function Notify(options) {
  var _this = this;

  if (!$('#notify').length) {
    $('body').append('<div id="notify"><style media="screen"> #notify { position: fixed; top: 20px; right: 25px; z-index: 9999; } #notify > div { display: none; position: relative; width: 300px; padding: .4em .8em; margin-bottom: .6em; border-radius: 2px; background-color: white; color: #2c3e50; font-size: 17px; cursor: pointer; transition: .4s; } </style></div>');
  }

  _this.options = options;
  _this.container = $('#notify');
  _this.template = $('<div><span></span></div>');

  if (!_this.options || typeof _this.options != 'object') {
    throw 'Options required';
  }
  if (!_this.options.text) {
    throw 'Options TEXT must not be empty';
  }

  if (_this.options.type) {
    var background = '';
    switch (_this.options.type) {
      case 'success':
        background = '#2ecc71';
      break;
      case 'info':
      case 'information':
        background = '#3498db';
      break;
      case 'warn':
      case 'warning':
        background = '#f9ca24';
      break;
      case 'error':
        background = '#e74c3c';
      break;
      default:
        throw 'Type not found';
    }
    if (background) {
      _this.template.css('background-color', background);
      _this.template.css('color', 'white');
    }
  }

  _this.id = 'noty_'+Math.random().toString(36).substring(2);
  _this.template.attr('id', _this.id);
  _this.template.find('span').text(_this.options.text);
  _this.template.css('right', -(300+parseInt(_this.container.css('right')))+'px');

};

Notify.prototype.show = function () {
  var _this = this;

  if (!_this.container.find('#'+_this.id).length) {
    _this.container.append(_this.template);
  }

  _this.template.css('display', 'block');
  _this.template.off('click').on('click', function() {
    _this.close();
  });
  setTimeout(function() {
    _this.template.css('right', '0');
  }, 100);

  if (_this.options.delay !== 0) {
    _this.closeTime = setTimeout(function() {
      _this.close();
    }, (_this.options.delay || 4500));
  }

  return _this;
};

Notify.prototype.close = function () {
  var _this = this;
  if (!_this.container.find('#'+_this.id).length) return;

  clearTimeout(_this.closeTime);
  _this.template.css('right', -(300+parseInt(_this.container.css('right')))+'px');

  setTimeout(function() {
    _this.template.remove();
  }, 500);

  return _this;
};