天天看点

【前端H5】bootstrap-table表格插件使用js设置高度及高度自适应

用js控制bootstrapTable的高度有几种方法

方法一:

<table class="table-striped qiliangqifei-tab" id="qiliangqifei">
			   <thead>
				  <tr>
					 <th data-valign="middle" >气费年月</th>
					 <th>当期气量 </br > Sm<sup>3</sup></th>
					 <th>当期气费 </br >(元)</th>
				  </tr>
			   </thead>
			   <tbody>
				 				  <tr>
					 <td>2016-12</td>
					 <td>100</td>
					 <td>100</td>
				  </tr>

				  <tr>
					 <td>2016-10</td>
					 <td>100</td>
					 <td>100</td>
				  </tr>
				 
			   </tbody>
			</table>

 <script type="text/javascript">
 $(document).ready( function (){
        $( '#qiliangqifei' ).bootstrapTable( { height: 260 } );
});
 </script>
           

方法二:

<table class="table-striped " data-toggle="table" data-height="350" id="qiliangqifei">
			   <thead>
				  <tr>
					 <th data-valign="middle" >气费年月</th>
					 <th>当期气量 </br > Sm<sup>3</sup></th>
					 <th>当期气费 </br >(元)</th>
				  </tr>
			   </thead>
			   <tbody>
				 				  <tr>
					 <td>2016-12</td>
					 <td>100</td>
					 <td>100</td>
				  </tr>

				  <tr>
					 <td>2016-10</td>
					 <td>100</td>
					 <td>100</td>
				  </tr>
				 
			   </tbody>
			</table>

<script type="text/javascript">
   $('#qiliangqifei').bootstrapTable({height:$(window).height()-120}); 
</script>
           

两者的区别是table元素中第二种方法是含有data-toggle="table" 及data-height="350",js调用时不要写

$(document).ready(回调函数)

方法三:

<table class="table-striped " data-toggle="table" data-height="350"  id="qiliangqifei">
			   <thead>
				  <tr>
					 <th data-valign="middle" >气费年月</th>
					 <th>当期气量 </br > Sm<sup>3</sup></th>
					 <th>当期气费 </br >(元)</th>
				  </tr>
			   </thead>
			   <tbody>
				 				  <tr>
					 <td>2016-12</td>
					 <td>100</td>
					 <td>100</td>
				  </tr>

				  <tr>
					 <td>2016-10</td>
					 <td>100</td>
					 <td>100</td>
				  </tr>
				 
			   </tbody>
			</table>

 <script type="text/javascript">
 $(document).ready( function (){
        $( '#qiliangqifei' ).bootstrapTable('resetView',{ height: 260 } );
});
 </script>
           

如果有$(document).ready(回调函数),需要加上"resetView" 否则不起作用

如果我们根据table里面的内容来确定container的高度,当内容的高度大于窗口的高度就有滚动条,当内容的高度小于窗口的高度,container的高度设置为内容的高度

完整的js如下:

$(document).ready( function (){
    //设置bootstrapTable起始的高度
	 $('#tableTest1').bootstrapTable({height:$(window).height()-120});
	//当表格内容的高度小于外面容器的高度,容器的高度设置为内容的高度,相反时容器设置为窗口的高度-160
     if($(".fixed-table-body table").height()<$(".fixed-table-container").height()){
	 $(".fixed-table-container").css({"padding-bottom":"0px",height:$(".fixed-table-body table").height()+20});
    // 是当内容少时,使用搜索功能高度保持不变
	 $('#tableTest1').bootstrapTable('resetView',{height:"auto"});
	}else{
     $(".fixed-table-container").css({height:$(window).height()-160});
 }
 
   });
 
</script>
           

继续阅读