更改BootstrapTable.prototype.resetView
方法,以支持高度百分比定义,适应不同高度屏幕
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的完整代码:
<div class="jb51code">
<pre class="brush: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,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 = $('').addClass('fixed-table-scroll-inner'),outer = $('').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,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',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,footerStyle: function (row,onAll: function (name,args) {
return false;
},onClickCell: function (field,value,row,$element) {
return false;
},onDblClickCell: function (field,onClickRow: function (item,onDblClickRow: function (item,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,$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,totalRows);
},formatDetailPagination: function (totalRows) {
return sprintf('Showing %s rows',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,center
falign: undefined,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,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">