city-picker.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*!
  2. * CityPicker v1.1.0
  3. * https://github.com/tshi0912/citypicker
  4. *
  5. * Copyright (c) 2015-2016 Tao Shi
  6. * Released under the MIT license
  7. *
  8. * Date: 2016-09-09T12:11:57.119Z
  9. */
  10. (function (factory) {
  11. if (typeof define === 'function' && define.amd) {
  12. // AMD. Register as anonymous module.
  13. define(['jquery', 'ChineseDistricts'], factory);
  14. } else if (typeof exports === 'object') {
  15. // Node / CommonJS
  16. factory(require('jquery'), require('ChineseDistricts'));
  17. } else {
  18. // Browser globals.
  19. factory(jQuery, ChineseDistricts);
  20. }
  21. })(function ($, ChineseDistricts) {
  22. 'use strict';
  23. if (typeof ChineseDistricts === 'undefined') {
  24. throw new Error('The file "city-picker.data.js" must be included first!');
  25. }
  26. var NAMESPACE = 'citypicker';
  27. var EVENT_CHANGE = 'change.' + NAMESPACE;
  28. var PROVINCE = 'province';
  29. var CITY = 'city';
  30. var DISTRICT = 'district';
  31. function CityPicker(element, options) {
  32. this.$element = $(element);
  33. this.$dropdown = null;
  34. this.options = $.extend({}, CityPicker.DEFAULTS, $.isPlainObject(options) && options);
  35. this.active = false;
  36. this.dems = [];
  37. this.needBlur = false;
  38. this.init();
  39. }
  40. CityPicker.prototype = {
  41. constructor: CityPicker,
  42. init: function () {
  43. this.defineDems();
  44. this.render();
  45. this.bind();
  46. this.active = true;
  47. },
  48. render: function () {
  49. var p = this.getPosition(),
  50. placeholder = this.$element.attr('placeholder') || this.options.placeholder,
  51. textspan = '<span class="city-picker-span" style="' +
  52. this.getWidthStyle(p.width) + 'height:' +
  53. p.height + 'px;line-height:' + (p.height - 1) + 'px;">' +
  54. (placeholder ? '<span class="placeholder">' + placeholder + '</span>' : '') +
  55. '<span class="title"></span><div class="arrow"></div>' + '</span>',
  56. dropdown = '<div class="city-picker-dropdown" style="left:0px;top:100%;' +
  57. this.getWidthStyle(p.width, true) + '">' +
  58. '<div class="city-select-wrap">' +
  59. '<div class="city-select-tab">' +
  60. '<a class="active" data-count="province">省份</a>' +
  61. (this.includeDem('city') ? '<a data-count="city">城市</a>' : '') +
  62. (this.includeDem('district') ? '<a data-count="district">区县</a>' : '') + '</div>' +
  63. '<div class="city-select-content">' +
  64. '<div class="city-select province" data-count="province"></div>' +
  65. (this.includeDem('city') ? '<div class="city-select city" data-count="city"></div>' : '') +
  66. (this.includeDem('district') ? '<div class="city-select district" data-count="district"></div>' : '') +
  67. '</div></div>';
  68. this.$element.addClass('city-picker-input');
  69. this.$textspan = $(textspan).insertAfter(this.$element);
  70. this.$dropdown = $(dropdown).insertAfter(this.$textspan);
  71. var $select = this.$dropdown.find('.city-select');
  72. // setup this.$province, this.$city and/or this.$district object
  73. $.each(this.dems, $.proxy(function (i, type) {
  74. this['$' + type] = $select.filter('.' + type + '');
  75. }, this));
  76. this.refresh();
  77. },
  78. refresh: function (force) {
  79. // clean the data-item for each $select
  80. var $select = this.$dropdown.find('.city-select');
  81. $select.data('item', null);
  82. // parse value from value of the target $element
  83. var val = this.$element.val() || '';
  84. val = val.split('/');
  85. $.each(this.dems, $.proxy(function (i, type) {
  86. if (val[i] && i < val.length) {
  87. this.options[type] = val[i];
  88. } else if (force) {
  89. this.options[type] = '';
  90. }
  91. this.output(type);
  92. }, this));
  93. this.tab(PROVINCE);
  94. this.feedText();
  95. this.feedVal();
  96. },
  97. defineDems: function () {
  98. var stop = false;
  99. $.each([PROVINCE, CITY, DISTRICT], $.proxy(function (i, type) {
  100. if (!stop) {
  101. this.dems.push(type);
  102. }
  103. if (type === this.options.level) {
  104. stop = true;
  105. }
  106. }, this));
  107. },
  108. includeDem: function (type) {
  109. return $.inArray(type, this.dems) !== -1;
  110. },
  111. getPosition: function () {
  112. var p, h, w, s, pw;
  113. p = this.$element.position();
  114. s = this.getSize(this.$element);
  115. h = s.height;
  116. w = s.width;
  117. if (this.options.responsive) {
  118. pw = this.$element.offsetParent().width();
  119. if (pw) {
  120. w = w / pw;
  121. if (w > 0.99) {
  122. w = 1;
  123. }
  124. w = w * 100 + '%';
  125. }
  126. }
  127. return {
  128. top: p.top || 0,
  129. left: p.left || 0,
  130. height: h,
  131. width: w
  132. };
  133. },
  134. getSize: function ($dom) {
  135. var $wrap, $clone, sizes;
  136. if (!$dom.is(':visible')) {
  137. $wrap = $("<div />").appendTo($("body"));
  138. $wrap.css({
  139. "position": "absolute !important",
  140. "visibility": "hidden !important",
  141. "display": "block !important"
  142. });
  143. $clone = $dom.clone().appendTo($wrap);
  144. sizes = {
  145. width: $clone.outerWidth(),
  146. height: $clone.outerHeight()
  147. };
  148. $wrap.remove();
  149. } else {
  150. sizes = {
  151. width: $dom.outerWidth(),
  152. height: $dom.outerHeight()
  153. };
  154. }
  155. return sizes;
  156. },
  157. getWidthStyle: function (w, dropdown) {
  158. if (this.options.responsive && !$.isNumeric(w)) {
  159. return 'width:' + w + ';';
  160. } else {
  161. return 'width:' + (dropdown ? Math.max(320, w) : w) + 'px;';
  162. }
  163. },
  164. bind: function () {
  165. var $this = this;
  166. $(document).on('click', (this._mouteclick = function (e) {
  167. var $target = $(e.target);
  168. var $dropdown, $span, $input;
  169. if ($target.is('.city-picker-span')) {
  170. $span = $target;
  171. } else if ($target.is('.city-picker-span *')) {
  172. $span = $target.parents('.city-picker-span');
  173. }
  174. if ($target.is('.city-picker-input')) {
  175. $input = $target;
  176. }
  177. if ($target.is('.city-picker-dropdown')) {
  178. $dropdown = $target;
  179. } else if ($target.is('.city-picker-dropdown *')) {
  180. $dropdown = $target.parents('.city-picker-dropdown');
  181. }
  182. if ((!$input && !$span && !$dropdown) ||
  183. ($span && $span.get(0) !== $this.$textspan.get(0)) ||
  184. ($input && $input.get(0) !== $this.$element.get(0)) ||
  185. ($dropdown && $dropdown.get(0) !== $this.$dropdown.get(0))) {
  186. $this.close(true);
  187. }
  188. }));
  189. this.$element.on('change', (this._changeElement = $.proxy(function () {
  190. this.close(true);
  191. this.refresh(true);
  192. }, this))).on('focus', (this._focusElement = $.proxy(function () {
  193. this.needBlur = true;
  194. this.open();
  195. }, this))).on('blur', (this._blurElement = $.proxy(function () {
  196. if (this.needBlur) {
  197. this.needBlur = false;
  198. this.close(true);
  199. }
  200. }, this)));
  201. this.$textspan.on('click', function (e) {
  202. var $target = $(e.target), type;
  203. $this.needBlur = false;
  204. if ($target.is('.select-item')) {
  205. type = $target.data('count');
  206. $this.open(type);
  207. } else {
  208. if ($this.$dropdown.is(':visible')) {
  209. $this.close();
  210. } else {
  211. $this.open();
  212. }
  213. }
  214. }).on('mousedown', function () {
  215. $this.needBlur = false;
  216. });
  217. this.$dropdown.on('click', '.city-select a', function () {
  218. var $select = $(this).parents('.city-select');
  219. var $active = $select.find('a.active');
  220. var last = $select.next().length === 0;
  221. $active.removeClass('active');
  222. $(this).addClass('active');
  223. if ($active.data('code') !== $(this).data('code')) {
  224. $select.data('item', {
  225. address: $(this).attr('title'), code: $(this).data('code')
  226. });
  227. $(this).trigger(EVENT_CHANGE);
  228. $this.feedText();
  229. $this.feedVal(true);
  230. if (last) {
  231. $this.close();
  232. }
  233. }
  234. }).on('click', '.city-select-tab a', function () {
  235. if (!$(this).hasClass('active')) {
  236. var type = $(this).data('count');
  237. $this.tab(type);
  238. }
  239. }).on('mousedown', function () {
  240. $this.needBlur = false;
  241. });
  242. if (this.$province) {
  243. this.$province.on(EVENT_CHANGE, (this._changeProvince = $.proxy(function () {
  244. this.output(CITY);
  245. this.output(DISTRICT);
  246. this.tab(CITY);
  247. }, this)));
  248. }
  249. if (this.$city) {
  250. this.$city.on(EVENT_CHANGE, (this._changeCity = $.proxy(function () {
  251. this.output(DISTRICT);
  252. this.tab(DISTRICT);
  253. }, this)));
  254. }
  255. },
  256. open: function (type) {
  257. type = type || PROVINCE;
  258. this.$dropdown.show();
  259. this.$textspan.addClass('open').addClass('focus');
  260. this.tab(type);
  261. },
  262. close: function (blur) {
  263. this.$dropdown.hide();
  264. this.$textspan.removeClass('open');
  265. if (blur) {
  266. this.$textspan.removeClass('focus');
  267. }
  268. },
  269. unbind: function () {
  270. $(document).off('click', this._mouteclick);
  271. this.$element.off('change', this._changeElement);
  272. this.$element.off('focus', this._focusElement);
  273. this.$element.off('blur', this._blurElement);
  274. this.$textspan.off('click');
  275. this.$textspan.off('mousedown');
  276. this.$dropdown.off('click');
  277. this.$dropdown.off('mousedown');
  278. if (this.$province) {
  279. this.$province.off(EVENT_CHANGE, this._changeProvince);
  280. }
  281. if (this.$city) {
  282. this.$city.off(EVENT_CHANGE, this._changeCity);
  283. }
  284. },
  285. getText: function () {
  286. var text = '';
  287. this.$dropdown.find('.city-select')
  288. .each(function () {
  289. var item = $(this).data('item'),
  290. type = $(this).data('count');
  291. if (item) {
  292. text += ($(this).hasClass('province') ? '' : '/') + '<span class="select-item" data-count="' +
  293. type + '" data-code="' + item.code + '">' + item.address + '</span>';
  294. }
  295. });
  296. return text;
  297. },
  298. getPlaceHolder: function () {
  299. return this.$element.attr('placeholder') || this.options.placeholder;
  300. },
  301. feedText: function () {
  302. var text = this.getText();
  303. if (text) {
  304. this.$textspan.find('>.placeholder').hide();
  305. this.$textspan.find('>.title').html(this.getText()).show();
  306. } else {
  307. this.$textspan.find('>.placeholder').text(this.getPlaceHolder()).show();
  308. this.$textspan.find('>.title').html('').hide();
  309. }
  310. },
  311. getCode: function (count) {
  312. var obj = {}, arr = [];
  313. this.$textspan.find('.select-item')
  314. .each(function () {
  315. var code = $(this).data('code');
  316. var count = $(this).data('count');
  317. obj[count] = code;
  318. arr.push(code);
  319. });
  320. return count ? obj[count] : arr.join('/');
  321. },
  322. getVal: function () {
  323. var text = '';
  324. this.$dropdown.find('.city-select')
  325. .each(function () {
  326. var item = $(this).data('item');
  327. if (item) {
  328. text += ($(this).hasClass('province') ? '' : '/') + item.address;
  329. }
  330. });
  331. return text;
  332. },
  333. feedVal: function (trigger) {
  334. this.$element.val(this.getVal());
  335. if(trigger) {
  336. this.$element.trigger('cp:updated');
  337. }
  338. },
  339. output: function (type) {
  340. var options = this.options;
  341. //var placeholders = this.placeholders;
  342. var $select = this['$' + type];
  343. var data = type === PROVINCE ? {} : [];
  344. var item;
  345. var districts;
  346. var code;
  347. var matched = null;
  348. var value;
  349. if (!$select || !$select.length) {
  350. return;
  351. }
  352. item = $select.data('item');
  353. value = (item ? item.address : null) || options[type];
  354. code = (
  355. type === PROVINCE ? 86 :
  356. type === CITY ? this.$province && this.$province.find('.active').data('code') :
  357. type === DISTRICT ? this.$city && this.$city.find('.active').data('code') : code
  358. );
  359. districts = $.isNumeric(code) ? ChineseDistricts[code] : null;
  360. if ($.isPlainObject(districts)) {
  361. $.each(districts, function (code, address) {
  362. var provs;
  363. if (type === PROVINCE) {
  364. provs = [];
  365. for (var i = 0; i < address.length; i++) {
  366. if (address[i].address === value) {
  367. matched = {
  368. code: address[i].code,
  369. address: address[i].address
  370. };
  371. }
  372. provs.push({
  373. code: address[i].code,
  374. address: address[i].address,
  375. selected: address[i].address === value
  376. });
  377. }
  378. data[code] = provs;
  379. } else {
  380. if (address === value) {
  381. matched = {
  382. code: code,
  383. address: address
  384. };
  385. }
  386. data.push({
  387. code: code,
  388. address: address,
  389. selected: address === value
  390. });
  391. }
  392. });
  393. }
  394. $select.html(type === PROVINCE ? this.getProvinceList(data) :
  395. this.getList(data, type));
  396. $select.data('item', matched);
  397. },
  398. getProvinceList: function (data) {
  399. var list = [],
  400. $this = this,
  401. simple = this.options.simple;
  402. $.each(data, function (i, n) {
  403. list.push('<dl class="clearfix">');
  404. list.push('<dt>' + i + '</dt><dd>');
  405. $.each(n, function (j, m) {
  406. list.push(
  407. '<a' +
  408. ' title="' + (m.address || '') + '"' +
  409. ' data-code="' + (m.code || '') + '"' +
  410. ' class="' +
  411. (m.selected ? ' active' : '') +
  412. '">' +
  413. ( simple ? $this.simplize(m.address, PROVINCE) : m.address) +
  414. '</a>');
  415. });
  416. list.push('</dd></dl>');
  417. });
  418. return list.join('');
  419. },
  420. getList: function (data, type) {
  421. var list = [],
  422. $this = this,
  423. simple = this.options.simple;
  424. list.push('<dl class="clearfix"><dd>');
  425. $.each(data, function (i, n) {
  426. list.push(
  427. '<a' +
  428. ' title="' + (n.address || '') + '"' +
  429. ' data-code="' + (n.code || '') + '"' +
  430. ' class="' +
  431. (n.selected ? ' active' : '') +
  432. '">' +
  433. ( simple ? $this.simplize(n.address, type) : n.address) +
  434. '</a>');
  435. });
  436. list.push('</dd></dl>');
  437. return list.join('');
  438. },
  439. simplize: function (address, type) {
  440. address = address || '';
  441. if (type === PROVINCE) {
  442. return address.replace(/[省,市,自治区,壮族,回族,维吾尔]/g, '');
  443. } else if (type === CITY) {
  444. return address.replace(/[市,地区,回族,蒙古,苗族,白族,傣族,景颇族,藏族,彝族,壮族,傈僳族,布依族,侗族]/g, '')
  445. .replace('哈萨克', '').replace('自治州', '').replace(/自治县/, '');
  446. } else if (type === DISTRICT) {
  447. return address.length > 2 ? address.replace(/[市,区,县,旗]/g, '') : address;
  448. }
  449. },
  450. tab: function (type) {
  451. var $selects = this.$dropdown.find('.city-select');
  452. var $tabs = this.$dropdown.find('.city-select-tab > a');
  453. var $select = this['$' + type];
  454. var $tab = this.$dropdown.find('.city-select-tab > a[data-count="' + type + '"]');
  455. if ($select) {
  456. $selects.hide();
  457. $select.show();
  458. $tabs.removeClass('active');
  459. $tab.addClass('active');
  460. }
  461. },
  462. reset: function () {
  463. this.$element.val(null).trigger('change');
  464. },
  465. destroy: function () {
  466. this.unbind();
  467. this.$element.removeData(NAMESPACE).removeClass('city-picker-input');
  468. this.$textspan.remove();
  469. this.$dropdown.remove();
  470. }
  471. };
  472. CityPicker.DEFAULTS = {
  473. simple: false,
  474. responsive: false,
  475. placeholder: '请选择省/市/区',
  476. level: 'district',
  477. province: '',
  478. city: '',
  479. district: ''
  480. };
  481. CityPicker.setDefaults = function (options) {
  482. $.extend(CityPicker.DEFAULTS, options);
  483. };
  484. // Save the other citypicker
  485. CityPicker.other = $.fn.citypicker;
  486. // Register as jQuery plugin
  487. $.fn.citypicker = function (option) {
  488. var args = [].slice.call(arguments, 1);
  489. return this.each(function () {
  490. var $this = $(this);
  491. var data = $this.data(NAMESPACE);
  492. var options;
  493. var fn;
  494. if (!data) {
  495. if (/destroy/.test(option)) {
  496. return;
  497. }
  498. options = $.extend({}, $this.data(), $.isPlainObject(option) && option);
  499. $this.data(NAMESPACE, (data = new CityPicker(this, options)));
  500. }
  501. if (typeof option === 'string' && $.isFunction(fn = data[option])) {
  502. fn.apply(data, args);
  503. }
  504. });
  505. };
  506. $.fn.citypicker.Constructor = CityPicker;
  507. $.fn.citypicker.setDefaults = CityPicker.setDefaults;
  508. // No conflict
  509. $.fn.citypicker.noConflict = function () {
  510. $.fn.citypicker = CityPicker.other;
  511. return this;
  512. };
  513. $(function () {
  514. $('[data-toggle="city-picker"]').citypicker();
  515. });
  516. });