jquery.bulletin.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * @version 1.0.0
  4. * @github https://github.com/wenzhixin/bulletin
  5. * @blog http://wenzhixin.net.cn
  6. */
  7. (function($) {
  8. 'use strict';
  9. function Bulletin($el, options) {
  10. this.$el = $el;
  11. this.options = options;
  12. }
  13. Bulletin.prototype = {
  14. constructor : Bulletin,
  15. init: function() {
  16. var that = this;
  17. this.index = this.options.index;
  18. this.$li = this.$el.find('li');
  19. this.$li.eq(this.options.index).css('top', 0);
  20. if (this.$li.length > 1) {
  21. setTimeout(function() {
  22. that.scroll();
  23. }, this.options.interval);
  24. }
  25. this.events();
  26. },
  27. events: function() {
  28. var that = this;
  29. this.$el.find('.close').on('click', function() {
  30. that.$el.slideUp(that.options.speed);
  31. });
  32. },
  33. scroll: function() {
  34. var that = this,
  35. curIndex = this.index,
  36. dir = this.options.direction,
  37. speed = this.options.speed,
  38. height = this.$li.css('height');
  39. this.index = dir === 'down' ? this.index - 1 : this.index + 1;
  40. this.index = this.index % this.$li.length;
  41. this.$li.eq(curIndex).animate({top: (dir === 'down' ? '' : '-') + height}, speed);
  42. this.$li.eq(this.index).css('top', (dir === 'down' ? '-' : '') + height).animate({top: '0'}, speed);
  43. setTimeout(function() {
  44. that.scroll();
  45. }, this.options.interval);
  46. }
  47. };
  48. $.fn.bulletin = function() {
  49. var option = arguments[0],
  50. args = arguments,
  51. value,
  52. allowedMethods = [];
  53. this.each(function() {
  54. var $this = $(this),
  55. data = $this.data('bulletin'),
  56. options = $.extend({}, $.fn.bulletin.defaults, typeof option === 'object' && option);
  57. if (!data) {
  58. data = new Bulletin($this, options);
  59. $this.data('bulletin', data);
  60. }
  61. if (typeof option === 'string') {
  62. if ($.inArray(option, allowedMethods) < 0) {
  63. throw "Unknown method: " + option;
  64. }
  65. value = data[option](args[1]);
  66. } else {
  67. data.init();
  68. }
  69. });
  70. return value ? value : this;
  71. };
  72. $.fn.bulletin.defaults = {
  73. index: 0,
  74. interval: 3000,
  75. speed: 1000,
  76. direction: 'up' // up or down
  77. };
  78. })(jQuery);