場景
當數據條數過多時,鼠標下滑瀏覽表格數據,預期表頭一直在表格最上方,不隨鼠標滑動而被滑出屏幕
實現步驟
①引入所需css和js。
下載鏈接:https://pan.baidu.com/s/1_u66yoS4qY12MrXxysbCrA
提取碼:bcxp
<!--凍結表頭所需css-->
<link href="../static/css/bootstrap-table-fixed-header.css" rel="stylesheet"/>
<!--凍結表頭所需js-->
<script src="/js/bootstrap-table-fixed-header.js" type="text/javascript"></script>
②bootstrap-table表格放到div中,給div加個鬆開鼠標時執行的事件來模擬模擬鼠標滾動事件,以實現橫向滾動條的移動,表頭跟數據對應。並給表格添加class=“table table-striped table-fixed-header”
<!--bootstrap-table表格放到DIV中,加個鬆開鼠標時執行的事件來模擬模擬鼠標滾動事件,以實現橫向滾動條的移動,表頭跟數據對應-->
<div class="col-sm-12 select-table table-striped" style="overflow-x: auto;overflow-y: auto;" οnmοuseup="onmouseUP()">
<!--給表格class添加table table-striped table-fixed-header-->
<table id="bootstrap-table" class="table table-striped table-fixed-header"></table>
</div>
<script>
//onmouseup鬆開鼠標時執行
//模擬鼠標滾動事件,以實現橫向滾動條的移動,表頭跟數據對應
function onmouseUP(){
var scrollTop = document.getElementsByTagName("body")[0].scrollTop;
scrollTop -= 10;
$(".table-fixed-header").fixedHeader();
}
</script>
③給表格綁定凍結表頭事件
//5、固定表頭
$("#bootstrap-table").on("post-body.bs.table",function(){
$("#bootstrap-table thead").addClass("header");
$(".table-fixed-header").fixedHeader();
onmouseUP();
});
以上三步就能夠實現預期效果!記錄一下備忘~