city-picker.js 23 KB

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