jQueryプラグインの作成

今朝、私はGoogleマップに行き、そこで「トラフィック」レイヤーを見て喜んでいた。 すぐに、交通状況を表示する時間を選択するための興味深いインターフェースソリューションに目がいきました。

私はすぐに私のプロジェクトで同様の管理機関を使用したいと考えました。

プラグインがjQueryでどのように記述されているかを思い出してください。
画像

コントロールボディレイアウトを作成する


アプリケーションのグローバルネームスペースを散らかさないように、匿名のネームスペースでjQueryプラグインを作成することをお勧めします。

さらに、jQuery変数を$変数として使用するため、$ .noConflict()の規則が維持されます。

だから、ここにディスクがあります:

(function($) { var DATA_CMDS = 'timeslider-commands'; $.fn.timeslider = function(options) { var make = function() { var $this = $(this); if (options === null) { options = {}; } var $container = $('<div class="timeslider-container" unselectable="on"></div>'); var $downArrow = $('<div class="timeslider-arrow timeslider-down-arrow" unselectable="on"></div>'); var $upArrow = $('<div class="timeslider-arrow timeslider-up-arrow" unselectable="on"></div>'); var $sliderLine = $('<div class="timeslider-slider-line" unselectable="on"></div>'); var $labels = $('<div class="timeslider-labels" unselectable="on"></div>'); var $slider = $('<div class="timeslider-slider" unselectable="on"></div>'); var $input = $('<input type="hidden" />'); $sliderLine.append($slider); container.append($downArrow).append($sliderLine).append($upArrow); $container.append($labels); var $outmostContainer = $('<div class="timeslider-container"></div>'); $outmostContainer.append($container); $this.hide().after($outmostContainer); $this.data(DATA_CMDS, commands); }; return this.each(make); }; })(jQuery); 


元の統治体を非表示にし、レイアウトの後に配置します。 元の要素を削除することはできません。ユーザーは引き続きその要素を使用して対話できるからです。

スライダーの状態を変更する


  var updateSlider = function() { $slider.show().css('left', toPixels(value) + 'px'); }; var updateInput = function() { $input.val(toText(value)); }; var updateArrows = function() { if (isLeftEdge(value)) { $downArrow.addClass('timeslider-disabled'); } else { $downArrow.removeClass('timeslider-disabled'); } if (isRightEdge(value)) { $upArrow.addClass('timeslider-disabled'); } else { $upArrow.removeClass('timeslider-disabled'); } }; var pleaseSet = function(newValue) { if ('string' == typeof newValue) { newValue = fromText(newValue); } else { newValue = normalize(newValue); } value = newValue; updateInput(); updateSlider(); updateArrows(); return $this.change(); }; pleaseSet(options.value); 


ソース要素の変更イベントも生成することに注意してください。

JavaScriptを介してコントロールを管理するためのAPIを提供します


  var DATA_CMDS = 'timeslider-commands'; … var commands = { 'set': pleaseSet, 'get': pleaseGet }; $this.data(DATA_CMDS, commands); … var command = null; var follow = function() { var $this = $(this); return $this.data(DATA_CMDS)[command].call($this, options); }; if ('string' == typeof options) { command = options; options = arguments[1] || {}; var retValue = this; this.each(function() { retValue = follow.call(this); }); return retValue; } return this.each(make); }; 


最終版


ボタンの押下に対する応答を追加し、スタイルシートを描画すると、プラグインが機能します:)

デモページを作成し、GitHubにすべてをドロップするだけです。

github.com/akzhan/jquery-time-slider

Source: https://habr.com/ru/post/J101415/


All Articles