city-picker.js 22 KB

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