阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      插件 jQuery.CLNDR 中文 API 文档

      插件 jQuery.CLNDR 中文 API 文档 https://github.com/kylestetz/CLNDR

      一个使用 HTML 模板的 jQuery 日历插件

      CLNDR 是一个 jQuery 日历插件。它创建了 - 你之前听说过 - 因为缺乏真正动态的前端日历插件而感到沮丧。

      观看演示:kylestetz.github.io/CLNDR/

      下载

      • 发展:clndr.js
      • 制作:clndr.min.js 回到抢新版本?看看 CHANGELOG.md 文件。

      如果您想在特定浏览器或环境中运行某些测试,请 tests/test.html 包含基本功能测试列表。在提交时,请在提交拉取请求或问题之前运行这些(并在适当时添加)!

      依赖

      jQuery 和 Moment.js 依赖于。默认情况下,CLNDR 尝试使用 Underscore.js 的_.template() 功能,但是如果你指定一个自定义的渲染功能(见下面的文档)下划线不会在所有使用。

      因为他们的 API 是相同的,所以 Lo-Dash 的_.template() 功能也会起作用!只需包含 Lo-Dash 而不是 Underscore。

      使用 Bower

      您可以通过 Bower 安装 CLNDR :

      bower install clndr
      

      默认情况下不安装下划线。这允许您使用您想要的任何模板引擎。如果要在 templateUnderscore 中使用默认选项,只需将其安装为项目的依赖项: bower install underscore。

      CLNDR 使用 Angular

      如果要将 clndr 集成到 angular.js 站点,请开始使用此指令: angular-clndr。

      CLNDR 使用 Rails

      如果您正在构建 rails 应用程序,您可能会对 @sedx: clndr-rails 感兴趣 。

      简介:您编写标记

      那里有精彩且功能丰富的日历模块,它们都遇到了同样的问题:它们为你提供了必须使用的标记(通常是一堆很好的 JS)和样式。这会导致大量的黑客攻击,推动,拉动和烦恼,为什么 - 不能这样做我想要的场景。

      CLNDR 不生成标记(嗯,它有一些合理的默认值,但这是一个旁边)。相反,CLNDR 会要求您创建一个模板,作为回报,它会为您的模板提供一组很好的对象,这些对象可以让您在几行中启动并运行。

      ‘Days’数组

      这是典型的 CLNDR 模板。它有一个控制器部分和一个网格部分。

      <div class="clndr-controls">
          <div class="clndr-previous-button">&lsaquo;</div>
          <div class="month"><%= month %></div>
          <div class="clndr-next-button">&rsaquo;</div>
      </div>
      <div class="clndr-grid">
          <div class="days-of-the-week">
          <% _.each(daysOfTheWeek, function (day) { %>
              <div class="header-day"><%= day %></div>
          <% }); %>
              <div class="days">
              <% _.each(days, function (day) { %>
                  <div class="<%= day.classes %>"><%= day.day %></div>
              <% }); %>
              </div>
          </div>
      </div>
      

      该 days 数组包含我们制作日历所需的大部分内容。它的结构如下:

      {
          day: 5,
          events: [],
          classes: "day",
          date: moment("2015-12-31")
      }
      

      这样可以快速生成网格。days.classes 根据具体情况包含额外的课程:如果某一天是今天,“今天”将出现,以及当事件在当天登陆时的“事件”课程。

      传递你的活动

      CLNDR 接受事件作为对象数组:

      events = [
          {
              date: "YYYY-MM-DD or some other ISO Date format",
              and: "anything else"
          }
      ]
      

      date 除非您使用该 dateParameter 选项另行指定,否则 CLNDR 会查看 events 数组中对象的字段。在您的模板中, days 数组将自动神奇地包含这些事件对象。请参阅示例以演示事件如何填充 days 数组。

      用法

      CLNDR 倾向于在 Underscore 和时刻完成的令人敬畏的工作。这些是要求,除非您使用不同的渲染引擎,在这种情况下,Underscore 不是必需的)。确保将它们包含

      在 clndr.js 之前。它是一个 jQuery 插件,所以你自然也需要它。

      最低限度(CLNDR 包括默认模板):

      $('.parent-element').clndr();
      
      

      有了所有可用选项:

      $('.parent-element').clndr({
      
          // The template: this could be stored in markup as a
          //   <script type="text/template"></script>
          // or pulled in as a string
          template: clndrTemplate,
      
          // Determines which month to start with using either a date string or a
          // moment object.
          startWithMonth: "YYYY-MM-DD" or moment(),
      
          // Start the week off on Sunday (0), Monday (1), etc. Sunday is the default.
          // WARNING: if you are dealing with i18n and multiple languages, you
          // probably don't want this! See the "Internationalization" section below
          // for more.
          weekOffset: 0,
      
          // An array of day abbreviation labels. If you have moment.js set to a
          // different language, it will guess these for you! If for some reason that
          // doesn't work, use this...
          // WARNING: if you are dealing with i18n and multiple languages, you
          // probably don't want this! See the "Internationalization" section below
          // for more.
          daysOfTheWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
      
          // The target classnames that CLNDR will look for to bind events.
          // these are the defaults.
          targets: {
              day: 'day',
              empty: 'empty',
              nextButton: 'clndr-next-button',
              todayButton: 'clndr-today-button',
              previousButton: 'clndr-previous-button',
              nextYearButton: 'clndr-next-year-button',
              previousYearButton: 'clndr-previous-year-button',
          },
      
          // Custom classes to avoid styling issues. pass in only the classnames that
          // you wish to override. These are the defaults.
          classes: {
              past: "past",
              today: "today",
              event: "event",
              selected: "selected",
              inactive: "inactive",
              lastMonth: "last-month",
              nextMonth: "next-month",
              adjacentMonth: "adjacent-month",
          },
      
          // Click callbacks! The keyword 'this' is set to the clndr instance in all
          // callbacks.
          clickEvents: {
              // Fired whenever a calendar box is clicked. Returns a 'target' object
              // containing the DOM element, any events, and the date as a moment.js
              // object.
              click: function (target) {...},
      
              // Fired when a user goes to the current month and year. Returns a
              // moment.js object set to the correct month.
              today: function (month) {...},
      
              // Fired when a user goes forward a month. Returns a moment.js object
              // set to the correct month.
              nextMonth: function (month) {...},
      
              // Fired when a user goes back a month. Returns a moment.js object set
              // to the correct month.
              previousMonth: function (month) {...},
      
              // Fires any time the month changes as a result of a click action.
              // Returns a moment.js object set to the correct month.
              onMonthChange: function (month) {...},
      
              // Fired when the next year button is clicked. Returns a moment.js
              // object set to the correct month and year.
              nextYear: function (month) {...},
      
              // Fired when the previous year button is clicked. Returns a moment.js
              // object set to the correct month and year.
              previousYear: function (month) {...},
      
              // Fires any time the year changes as a result of a click action. If
              // onMonthChange is also set, it is fired BEFORE onYearChange. Returns
              // a moment.js object set to the correct month and year.
              onYearChange: function (month) {...},
      
              // Fired when a user goes forward a period. Returns moment.js objects
              // for the updated start and end date.
              nextInterval: function (start, end) {...},
      
              // Fired when a user goes back an interval. Returns moment.js objects for
              // the updated start and end date.
              previousInterval: function (start, end) {...},
      
              // Fired whenever the time period changes as configured in lengthOfTime.
              // Returns moment.js objects for the updated start and end date.
              onIntervalChange: function (start, end) {...}
          },
      
          // Use the 'touchstart' event instead of 'click'
          useTouchEvents: false,
      
          // This is called only once after clndr has been initialized and rendered.
          // use this to bind custom event handlers that don't need to be re-attached
          // every time the month changes (most event handlers fall in this category).
          // Hint: this.element refers to the parent element that holds the clndr,
          // and is a great place to attach handlers that don't get tossed out every
          // time the clndr is re-rendered.
          ready: function () { },
      
          // A callback when the calendar is done rendering. This is a good place
          // to bind custom event handlers (also see the 'ready' option above).
          doneRendering: function () {...},
      
          // An array of event objects
          events: [],
      
          // If you're supplying an events array, dateParameter points to the field
          // in your event object containing a date string. It's set to 'date' by
          // default.
          dateParameter: 'date',
      
          // CLNDR can accept events lasting more than one day! just pass in the
          // multiDayEvents option and specify what the start and end fields are
          // called within your event objects. See the example file for a working
          // instance of this.
          multiDayEvents: {
              endDate: 'endDate',
              startDate: 'startDate',
              // If you also have single day events with a different date field,
              // use the singleDay property and point it to the date field.
              singleDay: 'date'
          },
      
          // Show the dates of days in months adjacent to the current month. Defaults
          // to true.
          showAdjacentMonths: true,
      
          // When days from adjacent months are clicked, switch the current month.
          // fires nextMonth/previousMonth/onMonthChange click callbacks. defaults to
          // false.
          adjacentDaysChangeMonth: false,
      
          // Always make the calendar six rows tall (42 days) so that every month has
          // a consistent height. defaults to 'false'.
          forceSixRows: null,
      
          // Set this to true, if you want the plugin to track the last clicked day.
          // If trackSelectedDate is true, "selected" class will always be applied
          // only to the most recently clicked date; otherwise - selectedDate will
          // not change.
          trackSelectedDate: false,
      
          // Set this, if you want a date to be "selected" (see classes.selected)
          // after plugin init. Defualts to null, no initially selected date.
          selectedDate: null,
      
          // Set this to true if you don't want `inactive` dates to be selectable.
          // This will only matter if you are using the `constraints` option.
          ignoreInactiveDaysInSelection: null,
      
          // CLNDR can render in any time interval!
          // You can specify if you want to render one or more months, or one ore more
          // days in the calendar, as well as the paging interval whenever forward or
          // back is triggered. If both months and days are null, CLNDR will default
          // to the standard monthly view.
          lengthOfTime: {
              // Set to an integer if you want to render one or more months, otherwise
              // leave this null
              months: null,
      
              // Set to an integer if you want to render one or more days, otherwise
              // leave this null. Setting this to 14 would render a 2-week calendar.
              days: null,
      
              // This is the amount of months or days that will move forward/back when
              // paging the calendar. With days=14 and interval=7, you would have a
              // 2-week calendar that pages forward and backward 1 week at a time.
              interval: 1
          },
      
          // Any other data variables you want access to in your template. This gets
          // passed into the template function.
          extras: {},
      
          // If you want to use a different templating language, here's your ticket.
          // Precompile your template (before you call clndr), pass the data from the
          // render function into your template, and return the result. The result
          // must be a string containing valid markup. The keyword 'this' is set to
          // the clndr instance in case you need access to any other properties.
          // More under 'Template Rendering Engine' below.
          render: function (data) {
              return '<div class="html data as a string"></div>';
          },
      
          // If you want to prevent the user from navigating the calendar outside
          // of a certain date range (e.g. if you are making a datepicker), specify
          // either the startDate, endDate, or both in the constraints option. You
          // can change these while the calendar is on the page... See documentation
          // below for more on this!
          constraints: {
              startDate: '2017-12-22',
              endDate: '2018-01-09'
          },
      
          // Optionally, you can pass a Moment instance to use instead of the CLNDR settings.
          // If you use moment you shouldn't use weekOffset and daysOfTheWeek
          // See https://github.com/kylestetz/CLNDR#internationalization for more information
          moment: null
      });
      

      您在模板中可以访问的所有内容:

      // An array of day-of-the-week abbreviations, shifted as requested using the
      // weekOffset parameter.
      daysOfTheWeek: ['S', 'M', 'T', etc...]
      
      // The number of 7-block calendar rows, in the event that you want to do some
      // looping with it
      numberOfRows: 5
      
      // The days array, documented in more detail above
      days: [{ day, classes, id, events, date }]
      
      // The month name- don't forget that you can do things like
      // month.substring(0, 1) and month.toLowerCase() in your template
      month: "May"
      
      // The year that the calendar is currently focused on
      year: "2013"
      
      // All of the events happening this month. This will be empty of the
      // lengthOfTime config option is set.
      eventsThisMonth: []
      // All of the events happening last month. This is only set if
      // showAdjacementMonths is true.
      eventsLastMonth: []
      // All of the events happening next month. This is only set if
      // showAdjacementMonths is true.
      eventsNextMonth: []
      
      // If you specified a custom lengthOfTime, you will have these instead.
      intervalEnd: (moment object)
      intervalStart: (moment object)
      eventsThisInterval: []
      
      // Anything you passed into the 'extras' property when creating the clndr
      extras: {}
      

      多日活动

      CLNDR 接受持续超过一天的活动。您只需要告诉它如何访问事件的开始和结束日期:

      var lotsOfEvents = [
          {
              end: '2013-11-08',
              start: '2013-11-04',
              title: 'Monday to Friday Event'
          }, {
              end: '2013-11-20',
              start: '2013-11-15',
              title: 'Another Long Event'
          }
      ];
      
      $('#calendar').clndr({
          events: lotsOfEvents,
          multiDayEvents: {
              endDate: 'end',
              startDate: 'start'
          }
      });
      

      在我的模板中循环几天时,“周一至周五事件”将被传递到开始日期和结束日期之间的每一天。有关此功能的演示,请参阅示例文件夹中的 index.html。

      混合多日和单日活动

      如果您还将单日事件与不同的日期字段混合在一起,则从 clndr 开始,v1.2.7 您可以指定 multiDayEvents 被调用 的第三个属性,singleDay 该属性引用单日事件的日期字段。

      var lotsOfMixedEvents = [
          {
              end: '2015-11-08',
              start: '2015-11-04',
              title: 'Monday to Friday Event'
          }, {
              end: '2015-11-20',
              start: '2015-11-15',
              title: 'Another Long Event'
          }, {
              title: 'Birthday',
              date: '2015-07-16'
          }
      ];
      
      $('#calendar').clndr({
          events: lotsOfEvents,
          multiDayEvents: {
              endDate: 'end',
              singleDay: 'date',
              startDate: 'start'
          }
      });
      

      自定义类

      day 可以自定义自动添加到对象的类,以避免样式冲突。该 classes 选项接受 today,event,past, lastMonth,nextMonth,adjacentMonth,和 inactive。仅传入您希望覆盖的类名,其余的将设置为默认值。

      在这个例子中,我们 my- 为所有类创建一个名称空间:

      clndr.customClasses = $('#custom-classes').clndr({
          classes: {
              past: "my-past",
              today: "my-today",
              event: "my-event",
              inactive: "my-inactive",
              lastMonth: "my-last-month",
              nextMonth: "my-next-month",
              adjacentMonth: "my-adjacent-month"
          }
      });
      

      要配置 day,empty 和下一首 / 上 / 今天 / 等。按钮类,使用用法部分中 targets 记录的选项 。

      约束和 Datepickers

      如果你是一个日期选择器,或者你只是想防止用户 next 在您的日历荷兰国际集团一路 2034,您可以通过一个 constraints 与选项 startDate,endDate 或两者规定:

      $('#calendar').clndr({
          constraints: {
              endDate: '2015-07-16',
              startDate: '2015-05-06'
          }
      });
      

      现在,您的日历的下一个和上一个按钮仅在此日期范围内有效。当他们成为残疾人时,他们会让课程“不活跃”,你可以用它来使它们变灰或添加 gif 火焰或其他任何东西。

      网格中超出范围的天数也将包含 inactive 该类。这意味着您需要添加单击回调并检查一天是否有该类 inactive。它看起来像这样:

      $('#calendar').clndr({
          constraints: {
              endDate: '2015-07-16',
              startDate: '2015-05-06'
          },
          clickEvents: {
              click: function (target) {
                  if (!$(target.element).hasClass('inactive')) {
                      console.log('You picked a valid date!');
                  } else {
                      console.log('That date is outside of the range.');
                  }
              }
          }
      });
      

      约束可以随时更新 clndr.options.constraints。如果进行了更改,请 render() 事后调用,以便 clndr 可以使用适当的类更新您的接口。

      myCalendar.options.constraints.startDate = '1999-12-31';
      myCalendar.render();
      

      确保它 startDate 来到之前 endDate!

      返回实例 / 公共 API

      可以保存 clndr 对象,以便稍后从 JS 调用它。有增加或设置月份或年份的功能。您还可以提供新的事件数组。

      // Create a CLNDR and save the instance as myCalendar
      var myCalendar = $('#myCalendar').clndr();
      
      // Go to the next month
      myCalendar.forward();
      
      // Go to the previous month
      myCalendar.back();
      
      // Set the month using a number from 0-11 or a month name
      myCalendar.setMonth(0);
      myCalendar.setMonth('February');
      
      // Go to the next year
      myCalendar.nextYear();
      
      // Go to the previous year
      myCalendar.previousYear();
      
      // Set the year
      myCalendar.setYear(1997);
      
      // Go to today:
      myCalendar.today();
      
      // Overwrite the extras. Note that this triggers a re-render of the calendar.
      myCalendar.setExtras(newExtras);
      
      // Change the events. Note that this triggers a re-render of the calendar.
      myCalendar.setEvents(newEventsArray);
      
      // Add events. Note that this triggers a re-render of the calendar.
      myCalendar.addEvents(additionalEventsArray);
      
      // Remove events.  All events for which the passed in function returns true will
      // be removed from the calendar. Note that this triggers a re-render of the
      // calendar.
      myCalendar.removeEvents(function (event) {
          return event.id == idToRemove;
      });
      
      // Destroy the clndr instance. This will empty the DOM node containing the
      // calendar.
      myCalendar.destroy();
      

      如果你正在服用的优势 onMonthChange 和 onYearChange 回调,您可能希望其触发 whenver 你打电话 setMonth,setYear,forward, back,等就在传递一个对象与参数 withCallbacks: true 如下:

      // Month will be set to February and then onMonthChange will be fired.
      myCalendar.setMonth("February", { withCallbacks: true });
      
      // Month will increment and onMonthChange, and possibly onYearChange, will be
      // fired.
      myCalendar.next({ withCallbacks: true });
      

      模板要求

      CLNDR 的结构使您在模板中不需要任何内容。

      <% _.each(days, function (day) { %>
      <div class='<%= day.classes %>'><%= day.day %></div>
      <% }); %>
      

      目前,CLNDR 在一天内设置类,‘calendar-day-2013-05-30’并使用它来确定用户点击它的日期。因此,点击事件仅在 days.classes 包含在您的日元素 class 属性中时才有效,如上所示。

      组态

      模板渲染引擎

      您可以将 render 函数作为选项传递,例如:

      var precompiledTemplate = myRenderingEngine.template($('#my-template').html());
      
      $('#my-calendar').clndr({
          render: function (data) {
              return precompiledTemplate(data);
          }
      });
      

      函数必须返回渲染操作的 HTML 结果。在这种情况下,您可以在代码中的其他位置预编译您的模板,因为如果它将使用 Underscore,CLNDR 只关心您的模板。

      如果您使用自己的渲染方法,则 Underscore 不是此插件的依赖项。

      已经使用 doT.js, Hogan.js, Handlebars.js, Mustache.js 和 Knockout.js 成功测试了 CLNDR。如果您使用其他语言取得成功,请与我们联系,这里将记录下来。

      这是一个使用 doT.js 的例子。…..

      标记:

      <script id="dot-template" type="text/template">
          <div class="clndr-controls">
              <div class="clndr-previous-button">&lsaquo;</div>
              <div class="month">{{= it.month }}</div>
              <div class="clndr-next-button">&rsaquo;</div>
          </div>
          <div class="clndr-grid">
              <div class="days-of-the-week">
              {{~it.daysOfTheWeek :day:index}}
                  <div class="header-day">{{= day }}</div>
              {{~}}
                  <div class="days">
                  {{~it.days :day:index}}
                      <div class="{{= day.classes }}">{{= day.day }}</div>
                  {{~}}
                  </div>
              </div>
          </div>
      </script>
      

      Javascript:

      var clndrTemplate = doT.template($('#dot-template').html());
      
      $('#calendar').clndr({
          render: function (data) {
              return clndrTemplate(data);
          }
      });
      

      这是使用 Mustache.js 的一个例子。…..

      标记:

      <script type="x-tmpl-mustache" id="calendar-tmpl">
          <div class="controls">
              <span class="clndr-previous-button">prev</span>
              <span class="month">{{month}}</span>
              <span class="year">{{year}}</span>
              <span class="clndr-next-button">next</span>
          </div>
          <div class="days-container">
              <div class="days">
                  <div class="headers">
                      {{#daysOfTheWeek}}
                          <div class="day-header">{{.}}</div>
                      {{/daysOfTheWeek}}
                  </div>
                  {{#days}}
                      <div class="{{classes}}" id="{{id}}">{{day}}</div>
                  {{/days}}
              </div>
          </div>
      </script>
      

      Javascript:

      $('#calendar').clndr({
          render: function (data) {
              return Mustache.render($('#calendar-tmpl').html(), data);
          },
      });
      

      国际化

      在 Moment.js 支持的情况下,CLNDR 支持国际化。通过将 Moment.js 实例配置为另一种语言,您可以在此处详细了解:在 Moment.js 中的 i18n,您也正在配置 CLNDR。

      如果您希望传入预配置的实例,可以 moment 在初始化 CLNDR 时将其作为 config 选项传入:

      // To change clndr to German use moment.local('de')
      moment.locale('de');
      
      // Make sure that your locale is Working correctly
      console.log(moment().calendar())
      // Returns "heute um 18:43 Uhr"
      
      $('#calendar').clndr({
          // Pass the moment instance to use your language settings
          moment: moment
      });
      

      如果您使用的是周末开始的周期(例如法语)的 moment.js 语言配置,CLNDR 将自动检测到这一点,并且不需要提供数组 weekOffset 或 daysOfTheWeek 数组。如果要反转此行为,则每个 moment.js 语言配置文件中都有一个字段 dow,您可以根据自己的喜好进行设置。

      使用 moment.js 的当前语言设置自动创建星期几缩写,但是如果这不符合您的需要,您应该使用该 daysOfTheWeek 选项覆盖它们。确保您提供的阵列在当前语言设置的一周中的同一天开始。 警告:不建议使用 daysOfTheWeek 并 weekOffset 结合使用不同的语言设置,这可能会让您头疼。

      下划线模板分隔符

      如果你不是一个球迷<% %>和<%= %>风格的分隔符,您可以提供 Underscore.js 用正则表达式的形式替代。有三个分隔符。…..

      interpolate,输出一个字符串(<%= %>默认情况下)

      转义,用于转义 HTML(<%- %>默认情况下)

      评估,评估 javascript(这是<% %>默认情况下)

      如果您对 Jinja2 / Twig / Nunjucks 样式分隔符更为熟悉,只需在实例化 clndr 之前调用它:

      // Switch to Jinja2/Twig/Nunjucks-style delimiters
      _.templateSettings = {
          escape: /\{\{\-(.+?)\}\}/g,
          evaluate: /\{\%(.+?)\%\}/g,
          interpolate: /\{\{(.+?)\}\}/g,
      };
      

      Internet Explorer 问题 如果您计划支持 IE8 及更低版本,则必须注意版本依赖性。你需要 jQuery 1.10.x 分支来支持 IE,如果你正在利用这个 constraints 功能,你需要使用一个版本的 moment.js <=2.1.0 或》=2.5.1。

      目录
      目录