让bootstrap-table支持高度百分比
程序员文章站
2022-05-03 09:06:40
更改BootstrapTable.prototype.resetView 方法,以支持高度百分比定义,适应不同高度屏幕 更改后的bootstrap-table.js的完整代码: /** * @author zhixin wen * version: ......
更改BootstrapTable.prototype.resetView 方法,以支持高度百分比定义,适应不同高度屏幕
BootstrapTable.prototype.resetView = function (params) { var padding = 0; if (params && params.height) { this.options.height = params.height; } this.$selectAll.prop('checked', this.$selectItem.length > 0 && this.$selectItem.length === this.$selectItem.filter(':checked').length); if (this.options.height) { var toolbarHeight = this.$toolbar.outerHeight(true), paginationHeight = this.$pagination.outerHeight(true), height = this.options.height;
//关键代码 if (this.options.height.toString().indexOf("%") != -1) { height = $(window).height() * (parseFloat(this.options.height) / 100); } height = height - toolbarHeight - paginationHeight; this.$tableContainer.css('height', height + 'px'); } if (this.options.cardView) { // remove the element css this.$el.css('margin-top', '0'); this.$tableContainer.css('padding-bottom', '0'); this.$tableFooter.hide(); return; } if (this.options.showHeader && this.options.height) { this.$tableHeader.show(); this.resetHeader(); padding += this.$header.outerHeight(); } else { this.$tableHeader.hide(); this.trigger('post-header'); } if (this.options.showFooter) { this.resetFooter(); if (this.options.height) { padding += this.$tableFooter.outerHeight() + 1; } } // Assign the correct sortable arrow this.getCaret(); this.$tableContainer.css('padding-bottom', padding + 'px'); this.trigger('reset-view'); };
更改后的bootstrap-table.js的完整代码:
/** * @author zhixin wen <wenzhixin2010@gmail.com> * version: 1.11.1 * https://github.com/wenzhixin/bootstrap-table/ */ (function ($) { 'use strict'; // TOOLS DEFINITION // ====================== var cachedWidth = null; // it only does '%s', and return '' when arguments are undefined var sprintf = function (str) { var args = arguments, flag = true, i = 1; str = str.replace(/%s/g, function () { var arg = args[i++]; if (typeof arg === 'undefined') { flag = false; return ''; } return arg; }); return flag ? str : ''; }; var getPropertyFromOther = function (list, from, to, value) { var result = ''; $.each(list, function (i, item) { if (item[from] === value) { result = item[to]; return false; } return true; }); return result; }; var getFieldIndex = function (columns, field) { var index = -1; $.each(columns, function (i, column) { if (column.field === field) { index = i; return false; } return true; }); return index; }; // http://jsfiddle.net/wenyi/47nz7ez9/3/ var setFieldIndex = function (columns) { var i, j, k, totalCol = 0, flag = []; for (i = 0; i < columns[0].length; i++) { totalCol += columns[0][i].colspan || 1; } for (i = 0; i < columns.length; i++) { flag[i] = []; for (j = 0; j < totalCol; j++) { flag[i][j] = false; } } for (i = 0; i < columns.length; i++) { for (j = 0; j < columns[i].length; j++) { var r = columns[i][j], rowspan = r.rowspan || 1, colspan = r.colspan || 1, index = $.inArray(false, flag[i]); if (colspan === 1) { r.fieldIndex = index; // when field is undefined, use index instead if (typeof r.field === 'undefined') { r.field = index; } } for (k = 0; k < rowspan; k++) { flag[i + k][index] = true; } for (k = 0; k < colspan; k++) { flag[i][index + k] = true; } } } }; var getScrollBarWidth = function () { if (cachedWidth === null) { var inner = $('<p/>').addClass('fixed-table-scroll-inner'), outer = $('<div/>').addClass('fixed-table-scroll-outer'), w1, w2; outer.append(inner); $('body').append(outer); w1 = inner[0].offsetWidth; outer.css('overflow', 'scroll'); w2 = inner[0].offsetWidth; if (w1 === w2) { w2 = outer[0].clientWidth; } outer.remove(); cachedWidth = w1 - w2; } return cachedWidth; }; var calculateObjectValue = function (self, name, args, defaultValue) { var func = name; if (typeof name === 'string') { // support obj.func1.func2 var names = name.split('.'); if (names.length > 1) { func = window; $.each(names, function (i, f) { func = func[f]; }); } else { func = window[name]; } } if (typeof func === 'object') { return func; } if (typeof func === 'function') { return func.apply(self, args || []); } if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) { return sprintf.apply(this, [name].concat(args)); } return defaultValue; }; var compareObjects = function (objectA, objectB, compareLength) { // Create arrays of property names var objectAProperties = Object.getOwnPropertyNames(objectA), objectBProperties = Object.getOwnPropertyNames(objectB), propName = ''; if (compareLength) { // If number of properties is different, objects are not equivalent if (objectAProperties.length !== objectBProperties.length) { return false; } } for (var i = 0; i < objectAProperties.length; i++) { propName = objectAProperties[i]; // If the property is not in the object B properties, continue with the next property if ($.inArray(propName, objectBProperties) > -1) { // If values of same property are not equal, objects are not equivalent if (objectA[propName] !== objectB[propName]) { return false; } } } // If we made it this far, objects are considered equivalent return true; }; var escapeHTML = function (text) { if (typeof text === 'string') { return text .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/`/g, '`'); } return text; }; var getRealDataAttr = function (dataAttr) { for (var attr in dataAttr) { var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase(); if (auxAttr !== attr) { dataAttr[auxAttr] = dataAttr[attr]; delete dataAttr[attr]; } } return dataAttr; }; var getItemField = function (item, field, escape) { var value = item; if (typeof field !== 'string' || item.hasOwnProperty(field)) { return escape ? escapeHTML(item[field]) : item[field]; } var props = field.split('.'); for (var p in props) { if (props.hasOwnProperty(p)) { value = value && value[props[p]]; } } return escape ? escapeHTML(value) : value; }; var isIEBrowser = function () { return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)); }; var objectKeys = function () { // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } }; // BOOTSTRAP TABLE CLASS DEFINITION // ====================== var BootstrapTable = function (el, options) { this.options = options; this.$el = $(el); this.$el_ = this.$el.clone(); this.timeoutId_ = 0; this.timeoutFooter_ = 0; this.init(); }; BootstrapTable.DEFAULTS = { classes: 'table table-hover', sortClass: undefined, locale: undefined, height: undefined, undefinedText: '-', sortName: undefined, sortOrder: 'asc', sortStable: false, striped: false, columns: [[]], data: [], totalField: 'total', dataField: 'rows', method: 'get', url: undefined, ajax: undefined, cache: true, contentType: 'application/json', dataType: 'json', ajaxOptions: {}, queryParams: function (params) { return params; }, queryParamsType: 'limit', // undefined responseHandler: function (res) { return res; }, pagination: false, onlyInfoPagination: false, paginationLoop: true, sidePagination: 'client', // client or server totalRows: 0, // server side need to set pageNumber: 1, pageSize: 10, pageList: [10, 25, 50, 100], paginationHAlign: 'right', //right, left paginationVAlign: 'bottom', //bottom, top, both paginationDetailHAlign: 'left', //right, left paginationPreText: '‹', paginationNextText: '›', search: false, searchOnEnterKey: false, strictSearch: false, searchAlign: 'right', selectItemName: 'btSelectItem', showHeader: true, showFooter: false, showColumns: false, showPaginationSwitch: false, showRefresh: false, showToggle: false, buttonsAlign: 'right', smartDisplay: true, escape: false, minimumCountColumns: 1, idField: undefined, uniqueId: undefined, cardView: false, detailView: false, detailFormatter: function (index, row) { return ''; }, trimOnSearch: true, clickToSelect: false, singleSelect: false, toolbar: undefined, toolbarAlign: 'left', checkboxHeader: true, sortable: true, silentSort: true, maintainSelected: false, searchTimeOut: 500, searchText: '', iconSize: undefined, buttonsClass: 'default', iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome) icons: { paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down', paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up', refresh: 'glyphicon-refresh icon-refresh', toggle: 'glyphicon-list-alt icon-list-alt', columns: 'glyphicon-th icon-th', detailOpen: 'glyphicon-plus icon-plus', detailClose: 'glyphicon-minus icon-minus' }, customSearch: $.noop, customSort: $.noop, rowStyle: function (row, index) { return {}; }, rowAttributes: function (row, index) { return {}; }, footerStyle: function (row, index) { return {}; }, onAll: function (name, args) { return false; }, onClickCell: function (field, value, row, $element) { return false; }, onDblClickCell: function (field, value, row, $element) { return false; }, onClickRow: function (item, $element) { return false; }, onDblClickRow: function (item, $element) { return false; }, onSort: function (name, order) { return false; }, onCheck: function (row) { return false; }, onUncheck: function (row) { return false; }, onCheckAll: function (rows) { return false; }, onUncheckAll: function (rows) { return false; }, onCheckSome: function (rows) { return false; }, onUncheckSome: function (rows) { return false; }, onLoadSuccess: function (data) { return false; }, onLoadError: function (status) { return false; }, onColumnSwitch: function (field, checked) { return false; }, onPageChange: function (number, size) { return false; }, onSearch: function (text) { return false; }, onToggle: function (cardView) { return false; }, onPreBody: function (data) { return false; }, onPostBody: function () { return false; }, onPostHeader: function () { return false; }, onExpandRow: function (index, row, $detail) { return false; }, onCollapseRow: function (index, row) { return false; }, onRefreshOptions: function (options) { return false; }, onRefresh: function (params) { return false; }, onResetView: function () { return false; } }; BootstrapTable.LOCALES = {}; BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES.en = { formatLoadingMessage: function () { return 'Loading, please wait...'; }, formatRecordsPerPage: function (pageNumber) { return sprintf('%s rows per page', pageNumber); }, formatShowingRows: function (pageFrom, pageTo, totalRows) { return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows); }, formatDetailPagination: function (totalRows) { return sprintf('Showing %s rows', totalRows); }, formatSearch: function () { return 'Search'; }, formatNoMatches: function () { return 'No matching records found'; }, formatPaginationSwitch: function () { return 'Hide/Show pagination'; }, formatRefresh: function () { return 'Refresh'; }, formatToggle: function () { return 'Toggle'; }, formatColumns: function () { return 'Columns'; }, formatAllRows: function () { return 'All'; } }; $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']); BootstrapTable.COLUMN_DEFAULTS = { radio: false, checkbox: false, checkboxEnabled: true, field: undefined, title: undefined, titleTooltip: undefined, 'class': undefined, align: undefined, // left, right, center halign: undefined, // left, right, center falign: undefined, // left, right, center valign: undefined, // top, middle, bottom width: undefined, sortable: false, order: 'asc', // asc, desc visible: true, switchable: true, clickToSelect: true, formatter: undefined, footerFormatter: undefined, events: undefined, sorter: undefined, sortName: undefined, cellStyle: undefined, searchable: true, searchFormatter: true, cardVisible: true, escape: false }; BootstrapTable.EVENTS = { 'all.bs.table': 'onAll', 'click-cell.bs.table': 'onClickCell', 'dbl-click-cell.bs.table': 'onDblClickCell', 'click-row.bs.table': 'onClickRow', 'dbl-click-row.bs.table': 'onDblClickRow', 'sort.bs.table': 'onSort', 'check.bs.table': 'onCheck', 'uncheck.bs.table': 'onUncheck', 'check-all.bs.table': 'onCheckAll', 'uncheck-all.bs.table': 'onUncheckAll', 'check-some.bs.table': 'onCheckSome', 'uncheck-some.bs.table': 'onUncheckSome', 'load-success.bs.table': 'onLoadSuccess', 'load-error.bs.table': 'onLoadError', 'column-switch.bs.table': 'onColumnSwitch', 'page-change.bs.table': 'onPageChange', 'search.bs.table': 'onSearch', 'toggle.bs.table': 'onToggle', 'pre-body.bs.table': 'onPreBody', 'post-body.bs.table': 'onPostBody', 'post-header.bs.table': 'onPostHeader', 'expand-row.bs.table': 'onExpandRow', 'collapse-row.bs.table': 'onCollapseRow', 'refresh-options.bs.table': 'onRefreshOptions', 'reset-view.bs.table': 'onResetView', 'refresh.bs.table': 'onRefresh' }; BootstrapTable.prototype.init = function () { this.initLocale(); this.initContainer(); this.initTable(); this.initHeader(); this.initData(); this.initHiddenRows(); this.initFooter(); this.initToolbar(); this.initPagination(); this.initBody(); this.initSearchText(); this.initServer(); }; BootstrapTable.prototype.initLocale = function () { if (this.options.locale) { var parts = this.options.locale.split(/-|_/); parts[0].toLowerCase(); if (parts[1]) parts[1].toUpperCase(); if ($.fn.bootstrapTable.locales[this.options.locale]) { // locale as requested $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]); } else if ($.fn.bootstrapTable.locales[parts.join('-')]) { // locale with sep set to - (in case original was specified with _) $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]); } else if ($.fn.bootstrapTable.locales[parts[0]]) { // short locale language code (i.e. 'en') $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]); } } }; BootstrapTable.prototype.initContainer = function () { this.$container = $([ '<div class="bootstrap-table">', '<div class="fixed-table-toolbar"></div>', this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ? '<div class="fixed-table-pagination" style="clear: both;"></div>' : '', '<div class="fixed-table-container">', '<div class="fixed-table-header"><table></table></div>', '<div class="fixed-table-body">', '<div class="fixed-table-loading">', this.options.formatLoadingMessage(), '</div>', '</div>', '<div class="fixed-table-footer"><table><tr></tr></table></div>', this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ? '<div class="fixed-table-pagination"></div>' : '', '</div>', '</div>' ].join('')); this.$container.insertAfter(this.$el); this.$tableContainer = this.$container.find('.fixed-table-container'); this.$tableHeader = this.$container.find('.fixed-table-header'); this.$tableBody = this.$container.find('.fixed-table-body'); this.$tableLoading = this.$container.find('.fixed-table-loading'); this.$tableFooter = this.$container.find('.fixed-table-footer'); this.$toolbar = this.$container.find('.fixed-table-toolbar'); this.$pagination = this.$container.find('.fixed-table-pagination'); this.$tableBody.append(this.$el); this.$container.after('<div class="clearfix"></div>'); this.$el.addClass(this.options.classes); if (this.options.striped) { this.$el.addClass('table-striped'); } if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) { this.$tableContainer.addClass('table-no-bordered'); } }; BootstrapTable.prototype.initTable = function () { var that = this, columns = [], data = []; this.$header = this.$el.find('>thead'); if (!this.$header.length) { this.$header = $('<thead></thead>').appendTo(this.$el); } this.$header.find('tr').each(function () { var column = []; $(this).find('th').each(function () { // Fix #2014 - getFieldIndex and elsewhere assume this is string, causes issues if not if (typeof $(this).data('field') !== 'undefined') { $(this).data('field', $(this).data('field') + ''); } column.push($.extend({}, { title: $(this).html(), 'class': $(this).attr('class'), titleTooltip: $(this).attr('title'), rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined, colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined }, $(this).data())); }); columns.push(column); }); if (!$.isArray(this.options.columns[0])) { this.options.columns = [this.options.columns]; } this.options.columns = $.extend(true, [], columns, this.options.columns); this.columns = []; setFieldIndex(this.options.columns); $.each(this.options.columns, function (i, columns) { $.each(columns, function (j, column) { column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column); if (typeof column.fieldIndex !== 'undefined') { that.columns[column.fieldIndex] = column; } that.options.columns[i][j] = column; }); }); // if options.data is setting, do not process tbody data if (this.options.data.length) { return; } var m = []; this.$el.find('>tbody>tr').each(function (y) { var row = {}; // save tr's id, class and data-* attributes row._id = $(this).attr('id'); row._class = $(this).attr('class'); row._data = getRealDataAttr($(this).data()); $(this).find('>td').each(function (x) { var $this = $(this), cspan = +$this.attr('colspan') || 1, rspan = +$this.attr('rowspan') || 1, tx, ty; for (; m[y] && m[y][x]; x++); //skip already occupied cells in current row for (tx = x; tx < x + cspan; tx++) { //mark matrix elements occupied by current cell with true for (ty = y; ty < y + rspan; ty++) { if (!m[ty]) { //fill missing rows m[ty] = []; } m[ty][tx] = true; } } var field = that.columns[x].field; row[field] = $(this).html(); // save td's id, class and data-* attributes row['_' + field + '_id'] = $(this).attr('id'); row['_' + field + '_class'] = $(this).attr('class'); row['_' + field + '_rowspan'] = $(this).attr('rowspan'); row['_' + field + '_colspan'] = $(this).attr('colspan'); row['_' + field + '_title'] = $(this).attr('title'); row['_' + field + '_data'] = getRealDataAttr($(this).data()); }); data.push(row); }); this.options.data = data; if (data.length) this.fromHtml = true; }; BootstrapTable.prototype.initHeader = function () { var that = this, visibleColumns = {}, html = []; this.header = { fields: [], styles: [], classes: [], formatters: [], events: [], sorters: [], sortNames: [], cellStyles: [], searchables: [] }; $.each(this.options.columns, function (i, columns) { html.push('<tr>'); if (i === 0 && !that.options.cardView && that.options.detailView) { html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>', that.options.columns.length)); } $.each(columns, function (j, column) { var text = '', halign = '', // header align style align = '', // body align style style = '', class_ = sprintf(' class="%s"', column['class']), order = that.options.sortOrder || column.order, unitWidth = 'px', width = column.width; if (column.width !== undefined && (!that.options.cardView)) { if (typeof column.width === 'string') { if (column.width.indexOf('%') !== -1) { unitWidth = '%'; } } } if (column.width && typeof column.width === 'string') { width = column.width.replace('%', '').replace('px', ''); } halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align); align = sprintf('text-align: %s; ', column.align); style = sprintf('vertical-align: %s; ', column.valign); style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ? '36px' : (width ? width + unitWidth : undefined)); if (typeof column.fieldIndex !== 'undefined') { that.header.fields[column.fieldIndex] = column.field; that.header.styles[column.fieldIndex] = align + style; that.header.classes[column.fieldIndex] = class_; that.header.formatters[column.fieldIndex] = column.formatter; that.header.events[column.fieldIndex] = column.events; that.header.sorters[column.fieldIndex] = column.sorter; that.header.sortNames[column.fieldIndex] = column.sortName; that.header.cellStyles[column.fieldIndex] = column.cellStyle; that.header.searchables[column.fieldIndex] = column.searchable; if (!column.visible) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } visibleColumns[column.field] = column; } html.push('<th' + sprintf(' title="%s"', column.titleTooltip), column.checkbox || column.radio ? sprintf(' class="bs-checkbox %s"', column['class'] || '') : class_, sprintf(' style="%s"', halign + style), sprintf(' rowspan="%s"', column.rowspan), sprintf(' colspan="%s"', column.colspan), sprintf(' data-field="%s"', column.field), '>'); html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ? 'sortable both' : '')); text = that.options.escape ? escapeHTML(column.title) : column.title; if (column.checkbox) { if (!that.options.singleSelect && that.options.checkboxHeader) { text = '<input name="btSelectAll" type="checkbox" />'; } that.header.stateField = column.field; } if (column.radio) { text = ''; that.header.stateField = column.field; that.options.singleSelect = true; } html.push(text); html.push('</div>'); html.push('<div class="fht-cell"></div>'); html.push('</div>'); html.push('</th>'); }); html.push('</tr>'); }); this.$header.html(html.join('')); this.$header.find('th[data-field]').each(function (i) { $(this).data(visibleColumns[$(this).data('field')]); }); this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) { var target = $(this); if (that.options.detailView) { if (target.closest('.bootstrap-table')[0] !== that.$container[0]) return false; } if (that.options.sortable && target.parent().data().sortable) { that.onSort(event); } }); this.$header.children().children().off('keypress').on('keypress', function (event) { if (that.options.sortable && $(this).data().sortable) { var code = event.keyCode || event.which; if (code == 13) { //Enter keycode that.onSort(event); } } }); $(window).off('resize.bootstrap-table'); if (!this.options.showHeader || this.options.cardView) { this.$header.hide(); this.$tableHeader.hide(); this.$tableLoading.css('top', 0); } else { this.$header.show(); this.$tableHeader.show(); this.$tableLoading.css('top', this.$header.outerHeight() + 1); // Assign the correct sortable arrow this.getCaret(); $(window).on('resize.bootstrap-table', $.proxy(this.resetWidth, this)); } this.$selectAll = this.$header.find('[name="btSelectAll"]'); this.$selectAll.off('click').on('click', function () { var checked = $(this).prop('checked'); that[checked ? 'checkAll' : 'uncheckAll'](); that.updateSelected(); }); }; BootstrapTable.prototype.initFooter = function () { if (!this.options.showFooter || this.options.cardView) { this.$tableFooter.hide(); } else { this.$tableFooter.show(); } }; /** * @param data * @param type: append / prepend */ BootstrapTable.prototype.initData = function (data, type) { if (type === 'append') { this.data = this.data.concat(data); } else if (type === 'prepend') { this.data = [].concat(data).concat(this.data); } else { this.data = data || this.options.data; } // Fix #839 Records deleted when adding new row on filtered table if (type === 'append') { this.options.data = this.options.data.concat(data); } else if (type === 'prepend') { this.options.data = [].concat(data).concat(this.options.data); } else { this.options.data = this.data; } if (this.options.sidePagination === 'server') { return; } this.initSort(); }; BootstrapTable.prototype.initSort = function () { var that = this, name = this.options.sortName, order = this.options.sortOrder === 'desc' ? -1 : 1, index = $.inArray(this.options.sortName, this.header.fields), timeoutId = 0; if (this.options.customSort !== $.noop) { this.options.customSort.apply(this, [this.options.sortName, this.options.sortOrder]); return; } if (index !== -1) { if (this.options.sortStable) { $.each(this.data, function (i, row) { if (!row.hasOwnProperty('_position')) row._position = i; }); } this.data.sort(function (a, b) { if (that.header.sortNames[index]) { name = that.header.sortNames[index]; } var aa = getItemField(a, name, that.options.escape), bb = getItemField(b, name, that.options.escape), value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]); if (value !== undefined) { return order * value; } // Fix #161: undefined or null string sort bug. if (aa === undefined || aa === null) { aa = ''; } if (bb === undefined || bb === null) { bb = ''; } if (that.options.sortStable && aa === bb) { aa = a._position; bb = b._position; } // IF both values are numeric, do a numeric comparison if ($.isNumeric(aa) && $.isNumeric(bb)) { // Convert numerical values form string to float. aa = parseFloat(aa); bb = parseFloat(bb); if (aa < bb) { return order * -1; } return order; } if (aa === bb) { return 0; } // If value is not a string, convert to string if (typeof aa !== 'string') { aa = aa.toString(); } if (aa.localeCompare(bb) === -1) { return order * -1; } return order; }); if (this.options.sortClass !== undefined) { clearTimeout(timeoutId); timeoutId = setTimeout(function () { that.$el.removeClass(that.options.sortClass); var index = that.$header.find(sprintf('[data-field="%s"]', that.options.sortName).index() + 1); that.$el.find(sprintf('tr td:nth-child(%s)', index)) .addClass(that.options.sortClass); }, 250); } } }; BootstrapTable.prototype.onSort = function (event) { var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(), $this_ = this.$header.find('th').eq($this.index()); this.$header.add(this.$header_).find('span.order').remove(); if (this.options.sortName === $this.data('field')) { this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc'; } else { this.options.sortName = $this.data('field'); this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc'; } this.trigger('sort', this.options.sortName, this.options.sortOrder); $this.add($this_).data('order', this.options.sortOrder); // Assign the correct sortable arrow this.getCaret(); if (this.options.sidePagination === 'server') { this.initServer(this.options.silentSort); return; } this.initSort(); this.initBody(); }; BootstrapTable.prototype.initToolbar = function () { var that = this, html = [], timeoutId = 0, $keepOpen, $search, switchableCount = 0; if (this.$toolbar.find('.bs-bars').children().length) { $('body').append($(this.options.toolbar)); } this.$toolbar.html(''); if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') { $(sprintf('<div class="bs-bars pull-%s"></div>', this.options.toolbarAlign)) .appendTo(this.$toolbar) .append($(this.options.toolbar)); } // showColumns, showToggle, showRefresh html = [sprintf('<div class="columns columns-%s btn-group pull-%s">', this.options.buttonsAlign, this.options.buttonsAlign)]; if (typeof this.options.icons === 'string') { this.options.icons = calculateObjectValue(null, this.options.icons); } if (this.options.showPaginationSwitch) { html.push(sprintf('<button class="btn' + sprintf(' btn-%s', this.options.buttonsClass) + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="paginationSwitch" aria-label="pagination Switch" title="%s">', this.options.formatPaginationSwitch()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown), '</button>'); } if (this.options.showRefresh) { html.push(sprintf('<button class="btn' + sprintf(' btn-%s', this.options.buttonsClass) + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="refresh" aria-label="refresh" title="%s">', this.options.formatRefresh()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh), '</button>'); } if (this.options.showToggle) { html.push(sprintf('<button class="btn' + sprintf(' btn-%s', this.options.buttonsClass) + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="toggle" aria-label="toggle" title="%s">', this.options.formatToggle()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle), '</button>'); } if (this.options.showColumns) { html.push(sprintf('<div class="keep-open btn-group" title="%s">', this.options.formatColumns()), '<button type="button" aria-label="columns" class="btn' + sprintf(' btn-%s', this.options.buttonsClass) + sprintf(' btn-%s', this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">', sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns), ' <span class="caret"></span>', '</button>', '<ul class="dropdown-menu" role="menu">'); $.each(this.columns, function (i, column) { if (column.radio || column.checkbox) { return; } if (that.options.cardView && !column.cardVisible) { return; } var checked = column.visible ? ' checked="checked"' : ''; if (column.switchable) { html.push(sprintf('<li role="menuitem">' + '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' + '</li>', column.field, i, checked, column.title)); switchableCount++; } }); html.push('</ul>', '</div>'); } html.push('</div>'); // Fix #188: this.showToolbar is for extensions if (this.showToolbar || html.length > 2) { this.$toolbar.append(html.join('')); } if (this.options.showPaginationSwitch) { this.$toolbar.find('button[name="paginationSwitch"]') .off('click').on('click', $.proxy(this.togglePagination, this)); } if (this.options.showRefresh) { this.$toolbar.find('button[name="refresh"]') .off('click').on('click', $.proxy(this.refresh, this)); } if (this.options.showToggle) { this.$toolbar.find('button[name="toggle"]') .off('click').on('click', function () { that.toggleView(); }); } if (this.options.showColumns) { $keepOpen = this.$toolbar.find('.keep-open'); if (switchableCount <= this.options.minimumCountColumns) { $keepOpen.find('input').prop('disabled', true); } $keepOpen.find('li').off('click').on('click', function (event) { event.stopImmediatePropagation(); }); $keepOpen.find('input').off('click').on('click', function () { var $this = $(this); that.toggleColumn($(this).val(), $this.prop('checked'), false); that.trigger('column-switch', $(this).data('field'), $this.prop('checked')); }); } if (this.options.search) { html = []; html.push( '<div class="pull-' + this.options.searchAlign + ' search">', sprintf('<input class="form-control' + sprintf(' input-%s', this.options.iconSize) + '" type="text" placeholder="%s">', this.options.formatSearch()), '</div>'); this.$toolbar.append(html.join('')); $search = this.$toolbar.find('.search input'); $search.off('keyup drop blur').on('keyup drop blur', function (event) { if (that.options.searchOnEnterKey && event.keyCode !== 13) { return; } if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) { return; } clearTimeout(timeoutId); // doesn't matter if it's 0 timeoutId = setTimeout(function () { that.onSearch(event); }, that.options.searchTimeOut); }); if (isIEBrowser()) { $search.off('mouseup').on('mouseup', function (event) { clearTimeout(timeoutId); // doesn't matter if it's 0 timeoutId = setTimeout(function () { that.onSearch(event); }, that.options.searchTimeOut); }); } } }; BootstrapTable.prototype.onSearch = function (event) { var text = $.trim($(event.currentTarget).val()); // trim search input if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) { $(event.currentTarget).val(text); } if (text === this.searchText) { return; } this.searchText = text; this.options.searchText = text; this.options.pageNumber = 1; this.initSearch(); this.updatePagination(); this.trigger('search', text); }; BootstrapTable.prototype.initSearch = function () { var that = this; if (this.options.sidePagination !== 'server') { if (this.options.customSearch !== $.noop) { this.options.customSearch.apply(this, [this.searchText]); return; } var s = this.searchText && (this.options.escape ? escapeHTML(this.searchText) : this.searchText).toLowerCase(); var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns; // Check filter this.data = f ? $.grep(this.options.data, function (item, i) { for (var key in f) { if ($.isArray(f[key]) && $.inArray(item[key], f[key]) === -1 || !$.isArray(f[key]) && item[key] !== f[key]) { return false; } } return true; }) : this.options.data; this.data = s ? $.grep(this.data, function (item, i) { for (var j = 0; j < that.header.fields.length; j++) { if (!that.header.searchables[j]) { continue; } var key = $.isNumeric(that.header.fields[j]) ? parseInt(that.header.fields[j], 10) : that.header.fields[j]; var column = that.columns[getFieldIndex(that.columns, key)]; var value; if (typeof key === 'string') { value = item; var props = key.split('.'); for (var prop_index = 0; prop_index < props.length; prop_index++) { value = value[props[prop_index]]; } // Fix #142: respect searchForamtter boolean if (column && column.searchFormatter) { value = calculateObjectValue(column, that.header.formatters[j], [value, item, i], value); } } else { value = item[key]; } if (typeof value === 'string' || typeof value === 'number') { if (that.options.strictSearch) { if ((value + '').toLowerCase() === s) { return true; } } else { if ((value + '').toLowerCase().indexOf(s) !== -1) { return true; } } } } return false; }) : this.data; } }; BootstrapTable.prototype.initPagination = function () { if (!this.options.pagination) { this.$pagination.hide(); return; } else { this.$pagination.show(); } var that = this, html = [], $allSelected = false, i, from, to, $pageList, $first, $pre, $next, $last, $number, data = this.getData(), pageList = this.options.pageList; if (this.options.sidePagination !== 'server') { this.options.totalRows = data.length; } this.totalPages = 0; if (this.options.totalRows) { if (this.options.pageSize === this.options.formatAllRows()) { this.options.pageSize = this.options.totalRows; $allSelected = true; } else if (this.options.pageSize === this.options.totalRows) { // Fix #667 Table with pagination, // multiple pages and a search that matches to one page throws exception var pageLst = typeof this.options.pageList === 'string' ? this.options.pageList.replace('[', '').replace(']', '') .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList; if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) { $allSelected = true; } } this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1; this.options.totalPages = this.totalPages; } if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) { this.options.pageNumber = this.totalPages; } this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1; this.pageTo = this.options.pageNumber * this.options.pageSize; if (this.pageTo > this.options.totalRows) { this.pageTo = this.options.totalRows; } html.push( '<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">', '<span class="pagination-info">', this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) : this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows), '</span>'); if (!this.options.onlyInfoPagination) { html.push('<span class="page-list">'); var pageNumber = [ sprintf('<span class="btn-group %s">', this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ? 'dropdown' : 'dropup'), '<button type="button" class="btn' + sprintf(' btn-%s', this.options.buttonsClass) + sprintf(' btn-%s', this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">', '<span class="page-size">', $allSelected ? this.options.formatAllRows() : this.options.pageSize, '</span>', ' <span class="caret"></span>', '</button>', '<ul class="dropdown-menu" role="menu">' ]; if (typeof this.options.pageList === 'string') { var list = this.options.pageList.replace('[', '').replace(']', '') .replace(/ /g, '').split(','); pageList = []; $.each(list, function (i, value) { pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ? that.options.formatAllRows() : +value); }); } $.each(pageList, function (i, page) { if (!that.options.smartDisplay || i === 0 || pageList[i - 1] < that.options.totalRows) { var active; if ($allSelected) { active = page === that.options.formatAllRows() ? ' class="active"' : ''; } else { active = page === that.options.pageSize ? ' class="active"' : ''; } pageNumber.push(sprintf('<li role="menuitem"%s><a href="#">%s</a></li>', active, page)); } }); pageNumber.push('</ul></span>'); html.push(this.options.formatRecordsPerPage(pageNumber.join(''))); html.push('</span>'); html.push('</div>', '<div class="pull-' + this.options.paginationHAlign + ' pagination">', '<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">', '<li class="page-pre"><a href="#">' + this.options.paginationPreText + '</a></li>'); if (this.totalPages < 5) { from = 1; to = this.totalPages; } else { from = this.options.pageNumber - 2; to = from + 4; if (from < 1) { from = 1; to = 5; } if (to > this.totalPages) { to = this.totalPages; from = to - 4; } } if (this.totalPages >= 6) { if (this.options.pageNumber >= 3) { html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">', '<a href="#">', 1, '</a>', '</li>'); from++; } if (this.options.pageNumber >= 4) { if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) { from--; } else { html.push('<li class="page-first-separator disabled">', '<a href="#">...</a>', '</li>'); } to--; } } if (this.totalPages >= 7) { if (this.options.pageNumber >= (this.totalPages - 2)) { from--; } } if (this.totalPages == 6) { if (this.options.pageNumber >= (this.totalPages - 2)) { to++; } } else if (this.totalPages >= 7) { if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) { to++; } } for (i = from; i <= to; i++) { html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">', '<a href="#">', i, '</a>', '</li>'); } if (this.totalPages >= 8) { if (this.options.pageNumber <= (this.totalPages - 4)) { html.push('<li class="page-last-separator disabled">', '<a href="#">...</a>', '</li>'); } } if (this.totalPages >= 6) { if (this.options.pageNumber <= (this.totalPages - 3)) { html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">', '<a href="#">', this.totalPages, '</a>', '</li>'); } } html.push( '<li class="page-next"><a href="#">' + this.options.paginationNextText + '</a></li>', '</ul>', '</div>'); } this.$pagination.html(html.join('')); if (!this.options.onlyInfoPagination) { $pageList = this.$pagination.find('.page-list a'); $first = this.$pagination.find('.page-first'); $pre = this.$pagination.find('.page-pre'); $next = this.$pagination.find('.page-next'); $last = this.$pagination.find('.page-last'); $number = this.$pagination.find('.page-number'); if (this.options.smartDisplay) { if (this.totalPages <= 1) { this.$pagination.find('div.pagination').hide(); } if (pageList.length < 2 || this.options.totalRows <= pageList[0]) { this.$pagination.find('span.page-list').hide(); } // when data is empty, hide the pagination this.$pagination[this.getData().length ? 'show' : 'hide'](); } if (!this.options.paginationLoop) { if (this.options.pageNumber === 1) { $pre.addClass('disabled'); } if (this.options.pageNumber === this.totalPages) { $next.addClass('disabled'); } } if ($allSelected) { this.options.pageSize = this.options.formatAllRows(); } $pageList.off('click').on('click', $.proxy(this.onPageListChange, this)); $first.off('click').on('click', $.proxy(this.onPageFirst, this)); $pre.off('click').on('click', $.proxy(this.onPagePre, this)); $next.off('click').on('click', $.proxy(this.onPageNext, this)); $last.off('click').on('click', $.proxy(this.onPageLast, this)); $number.off('click').on('click', $.proxy(this.onPageNumber, this)); } }; BootstrapTable.prototype.updatePagination = function (event) { // Fix #171: IE disabled button can be clicked bug. if (event && $(event.currentTarget).hasClass('disabled')) { return; } if (!this.options.maintainSelected) { this.resetRows(); } this.initPagination(); if (this.options.sidePagination === 'server') { this.initServer(); } else { this.initBody(); } this.trigger('page-change', this.options.pageNumber, this.options.pageSize); }; BootstrapTable.prototype.onPageListChange = function (event) { var $this = $(event.currentTarget); $this.parent().addClass('active').siblings().removeClass('active'); this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ? this.options.formatAllRows() : +$this.text(); this.$toolbar.find('.page-size').text(this.options.pageSize); this.updatePagination(event); return false; }; BootstrapTable.prototype.onPageFirst = function (event) { this.options.pageNumber = 1; this.updatePagination(event); return false; }; BootstrapTable.prototype.onPagePre = function (event) { if ((this.options.pageNumber - 1) === 0) { this.options.pageNumber = this.options.totalPages; } else { this.options.pageNumber--; } this.updatePagination(event); return false; }; BootstrapTable.prototype.onPageNext = function (event) { if ((this.options.pageNumber + 1) > this.options.totalPages) { this.options.pageNumber = 1; } else { this.options.pageNumber++; } this.updatePagination(event); return false; }; BootstrapTable.prototype.onPageLast = function (event) { this.options.pageNumber = this.totalPages; this.updatePagination(event); return false; }; BootstrapTable.prototype.onPageNumber = function (event) { if (this.options.pageNumber === +$(event.currentTarget).text()) { return; } this.options.pageNumber = +$(event.currentTarget).text(); this.updatePagination(event); return false; }; BootstrapTable.prototype.initRow = function (item, i, data, parentDom) { var that = this, key, html = [], style = {}, csses = [], data_ = '', attributes = {}, htmlAttributes = []; if ($.inArray(item, this.hiddenRows) > -1) { return; } style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style); if (style && style.css) { for (key in style.css) { csses.push(key + ': ' + style.css[key]); } } attributes = calculateObjectValue(this.options, this.options.rowAttributes, [item, i], attributes); if (attributes) { for (key in attributes) { htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key]))); } } if (item._data && !$.isEmptyObject(item._data)) { $.each(item._data, function (k, v) { // ignore data-index if (k === 'index') { return; } data_ += sprintf(' data-%s="%s"', k, v); }); } html.push('<tr', sprintf(' %s', htmlAttributes.join(' ')), sprintf(' id="%s"', $.isArray(item) ? undefined : item._id), sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)), sprintf(' data-index="%s"', i), sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]), sprintf('%s', data_), '>' ); if (this.options.cardView) { html.push(sprintf('<td colspan="%s"&
赞 (0)
打赏
微信扫一扫
相关文章:
-
-
盒子模型的属性 宽高width/height 在CSS中,可以对任何块级元素设置显式高度。 如果指定高度大于显示内容所需高度,多余的高度会产生一个视... [阅读全文]
-
更改BootstrapTable.prototype.resetView 方法,以支持高度百分比定义,适应不同高度屏幕 更改后的bootstrap-... [阅读全文]
-
postfile方法 ... [阅读全文]
-
1、那节课老师讲尖端放电,联系到闪电, 说放电发生在尖端,讲完后老师问在山上突然下雨打闪电知道咋办吧? 别去树下,如果闪电频繁就找个低洼趴在地上。 学生A小声调... [阅读全文]
-
一、绝对定位 二、translate 三、flex display: flex; justify-content: center; align-it... [阅读全文]
-
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
上一篇: vue中路由验证和相应拦截的使用详解
下一篇: 热部署
发表评论