近期工作中,碰到甲方需求:给一个bootstrap table表格,增加表头和第一列不随滚动条动而变化。即:要求固定表头和第一列。
官网上给的例子,就那么配置了几项,轻松加随意的达到效果。然而实际开发中,却是颇费了一番周折。好像我之前有个同事没解决这个需求,客户就交给我了。
A.先说固定表头:
极其简单:给table加一个height属性,不管是HTML加还是js里加,都一样~
然后照官网的做了后,运行页面,你会发现TMD根本就不是那样的!!表头固定,时好是不好,骗子!
怎么回事呢?
翻找诸多资料,终于找到原因:我们项目里引用的bootstrap-table.js,里面源码:
if (this.options.showHeader && this.options.height) {
this.$tableHeader.show();
//注释掉下面两行 取消表头初始化解决表头和内容不对齐问题
//this.resetHeader();
//padding += this.$header.outerHeight();
}
不知道写这个的兄弟有没有自己测试过,反正我注释了之后,确实表头和数据对齐了,但是表头固定功能消失了.
将其反注释,对不齐了? 小问题:
.fht-cell{
width:120px!important;}
修改了这2处,应该表头🆗了。(我说之前,怎么死活搞不定,源码都有问题,还玩个蛋啊!)。
B. 接着说固定第一列:
照官网的,加个$('#table1').bootstrapTable('destroy'); $('#table1').bootstrapTable({。。。。 fixedColumns: true, fixedNumber: 1 //固定列数... });
这里不要机械照抄,看好中英文标点。
改好保存,运行页面,卧槽,神马情况,表格都歪三扭四,搞毛啊。又蒙了·~
网上找大神修改过 的源码:bootstrap-table-fixed-columns.css
.fixed-table-header-columns,
.fixed-table-body-columns {
position: absolute;
background-color: #fff;
display: none;
box-sizing: border-box;
overflow: hidden;
}
.fixed-table-header-columns .table,
.fixed-table-body-columns .table {
border-right: 1px solid #ddd;
}
.fixed-table-header-columns .table.table-no-bordered,
.fixed-table-body-columns .table.table-no-bordered {
border-right: 1px solid transparent;
}
.fixed-table-body-columns table {
position: absolute;
animation: none;
}
.bootstrap-table .table-hover > tbody > tr.hover > td{
background-color: #f5f5f5;
}
bootstrap-table-fixed-columns.js
/*
* v2.0
* fixed by LX.
* 官网源码修改版,以增加对IE和谷歌的支持.
*/
(function ($) {
'use strict';
$.extend($.fn.bootstrapTable.defaults, {
fixedColumns: false,
fixedNumber: 1
});
var BootstrapTable = $.fn.bootstrapTable.Constructor,
_initHeader = BootstrapTable.prototype.initHeader,
_initBody = BootstrapTable.prototype.initBody,
_resetView = BootstrapTable.prototype.resetView;
BootstrapTable.prototype.initFixedColumns = function () {
this.$fixedHeader = $([
'<div class="fixed-table-header-columns">',
'<table>',
'<thead></thead>',
'</table>',
'</div>'].join(''));
this.timeoutHeaderColumns_ = 0;
this.$fixedHeader.find('table').attr('class', this.$el.attr('class'));
this.$fixedHeaderColumns = this.$fixedHeader.find('thead');
this.$tableHeader.before(this.$fixedHeader);
this.$fixedBody = $([
'<div class="fixed-table-body-columns">',
'<table>'