你的位置:首页 > Java教程

[Java教程]js 选择控件 picker


 

首先预览图效果:

imageimage

概述:

只是一个选择器,选择器内可以有多个分类,但输入目标只有一个.比较适合上图所示的情况:需要用户选择一个开始时间,且时间是限定死的,这个开始时间可能是昨天今天或明天。这个插件就是用来解决这个问题的,我不是一个前端工程师,所以代码的依赖 JQuery,样式是从bootstrap-datetimepicker那扒下来的几个,下面就是代码部分。

代码:

JS:

  <script type="text/javascript">    !function ($) {      var Picker = function (element, options) {        var defaultContent = {          name: '',          data: [],          prefix: '',          suffix: '',          isShowData: true        }        var that = this;        this.element = $(element);        this.isInput = this.element.is('input');        this.container = options.container || 'body';        this.firstView = options.firstView;        this.isClose = options.isClose;        var template = ' <div class="picker dropdown-menu" id="pickerContainer" style="display:none;width:280px" >';        var content = options.content;                $.each(content, function (index, subelement) {          subelement = $.extend({}, defaultContent, subelement);          var temp = DPGlobal.template;          temp = temp.replace("{title}", subelement.name).replace("{prefix}", subelement.prefix).replace("{suffix}", subelement.suffix).replace('{displayStyle}', index == options.firstView ? '' : 'style="display:none;"')          .replace('{leftArrow}', 'glyphicon glyphicon-arrow-left').replace('{rightArrow}', 'glyphicon glyphicon-arrow-right');          if (index > 0) {            temp = temp.replace("{leftVisibility}", "visibility:visible;")          } else {            temp = temp.replace("{leftVisibility}", "visibility:hidden;")          }          if (index < (content.length - 1)) {            temp = temp.replace("{rightVisibility}", "visibility:visible;")          } else {            temp = temp.replace("{rightVisibility}", "visibility:hidden;")          }          var str = '';          $.each(subelement.data, function (index, e) {            str += '<span>' + e + '</span>';          });          temp = temp.replace("{body}", str);          template += temp;        });        template += '</div>';        this.pickerBody = $(template).appendTo(this.container) // 'body')			.on({			  click: $.proxy(this.click, this),			  mousedown: $.proxy(this.mousedown, this)			});        $(document).on('mousedown', function (e) {          // Clicked outside the datetimepicker, hide it          if ($(e.target).closest('.picker').length === 0) {            that.pickerBody.hide();          }          if (e.target == element[0]) {            that.pickerBody.css("left", element.offset().left);            that.pickerBody.css("top", element.offset().top + element.outerHeight());            that.initialize();            that.pickerBody.show();          }        });        $.proxy(this.initialize, this);      }      Picker.prototype = {        click: function (element) {          var $target = $(element.target);          if ($target.length == 1) {            switch ($target[0].nodeName.toLowerCase()) {              case 'i':                var $div = $target.closest('div');                switch ($target.closest('th').attr('class')) {                  case 'prev':                    $div.hide();                    $div.prev('div').show();                    break;                  case 'next':                    $div.hide();                    $div.next('div').show();                    break;                  default:                    break;                }                break;              case 'span':                //层次变换 if else                var $td = $target.closest('td');                if ($target.hasClass('active'))                  break;                $('#pickerContainer span').removeClass('active');                $target.addClass('active');                this.activeObj = $target;                this.setValue();                if (this.isClose)                  this.pickerBody.hide();                break;              default:                break;            }          }        },        setValue: function () {          var formatted = this.getFormattedDate();          if (!this.isInput) {            this.element.find('input').val(formatted);          } else {            this.element.val(formatted);          }        },        getFormattedDate: function (format) {          var $parentDiv = this.activeObj.closest('div');          return $parentDiv.attr('prefix') + this.activeObj.text() + $parentDiv.attr('suffix');        },        initialize: function () {          var $divs = this.pickerBody.find('div');          $divs.css('display', 'none');          $($divs[this.firstView]).removeAttr('style');        }              }      //DPGlobal      var DPGlobal = {        headTemplate: '<thead>' +                   '<tr>' +                   '<th class="prev" style="{leftVisibility} cursor:pointer;"><i class="{leftArrow}"/></th>' +                   '<th colspan="5" class="switch">{title}</th>' +                   '<th class="next" style="{rightVisibility} cursor:pointer;"><i class="{rightArrow}"/></th>' +                   '</tr>' +          '</thead>',        contTemplate: '<tbody><tr><td colspan="7">{body}</td></tr></tbody>',        footTemplate: '<tfoot><tr><th colspan="7">{foot}</th></tr></tfoot>'      };      DPGlobal.template = '<div prefix="{prefix}" suffix="{suffix}" {displayStyle}>\              <table class=" table-condensed">'+                     DPGlobal.headTemplate +                     DPGlobal.contTemplate +                     //DPGlobal.footTemplate +                     '</table>\              </div>';      //DPGlobal end      $.fn.picker = function (options) {        var defaults = {          content: [],          firstView: 0,          isClose: false        }        options = $.extend(defaults, options);        new Picker(this, $.extend({}, $.fn.picker.defaults, options));      }    }(window.jQuery)  </script>

CSS:

    @font-face {      font-family: 'Glyphicons Halflings';      src: url('fonts/glyphicons-halflings-regular.eot');      src: url('fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('fonts/glyphicons-halflings-regular.woff') format('woff'), url('fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');    }    .glyphicon {      position: relative;      top: 1px;      display: inline-block;      font-family: 'Glyphicons Halflings';      -webkit-font-smoothing: antialiased;      font-style: normal;      font-weight: normal;      line-height: 1;    }    .picker table tr td {      color: #999;    }    .picker tbody > tr > td {      padding: 5px;    }    .picker td, .picker th {      text-align: center;      width: 20px;      height: 20px;      -webkit-border-radius: 4px;      -moz-border-radius: 4px;      border-radius: 4px;      border: 0;    }    .picker table {      border-collapse: collapse;      border-spacing: 0;    }    .picker {      padding: 4px;      margin-top: 1px;      -webkit-border-radius: 4px;      -moz-border-radius: 4px;      border-radius: 4px;      direction: ltr;    }    .dropdown-menu {      position: absolute;      /*top: 100%;*/      left: 0;      z-index: 1000;      /*display: none;*/      float: left;      min-width: 160px;      padding: 5px 0;      margin: 2px 0 0;      font-size: 14px;      list-style: none;      background-color: #fff;      border: 1px solid #ccc;      border: 1px solid rgba(0,0,0,0.15);      border-radius: 4px;      -webkit-box-shadow: 0 6px 12px rgba(0,0,0,0.175);      box-shadow: 0 6px 12px rgba(0,0,0,0.175);      background-clip: padding-box;    }    .picker table tr td span:hover {      background: #eeeeee;      cursor: pointer;    }    .picker table tr td span {      display: block;      width: 23%;      height: 54px;      line-height: 54px;      float: left;      margin: 1%;      cursor: pointer;      -webkit-border-radius: 4px;      -moz-border-radius: 4px;      border-radius: 4px;    }    .picker table {      width: 100%;    }      .picker table tr td span.active {        background-color: #039;      }    .glyphicon-arrow-left:before {      content: "\e091";    }    .glyphicon-arrow-right:before {      content: "\e092";    }
 

页面代码:

 <script type="text/javascript">    $(function () {      $("input").picker({        content: [{          name: '本日',          data: ['0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40'],          prefix:'本日 '        }, {          name: '次日',          data: ['0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40'],          prefix: '次日 '        }, {          name: '未来',          data: ['0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40', '0:30', '2:30', '5:40', '6:40'],        }]      });    });  </script> </head><body>  <input type="text" value="123" style="position:absolute;left:200px;top:200px;" /></body>

    //$("input").picker({    //  content: [{    //    name: '',//head显示的文字    //    data: [],//数据    //    prefix: '',//前缀    //    suffix: ''//后缀    //  }],    //  firstView: 0, //启始视图,content数组中的第一个将会第一个显示    //  isClose: false //是否自动关闭    //});