Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Created November 1, 2020 09:43
Show Gist options
  • Save earlgreyxxx/9a3ddab47e73629c1fc97059788c8632 to your computer and use it in GitHub Desktop.
Save earlgreyxxx/9a3ddab47e73629c1fc97059788c8632 to your computer and use it in GitHub Desktop.
/******************************************************************************
thead固定テーブル
require following...
<div class="table-wrap" style="position: relative;">
<table>
<thead>...</thead>
<tbody>...</tbody>
</table>
</div>
<script type="text/javascript">
(function($) {
$('.table-wrap').headFixed();
})(jQuery);
</script>
要点としては、table要素を複製して、複製したテーブルはtheadだけを、元のテーブルはtbodyのみを表示するようにする。
その際 displayプロパティにすると元table,複製tableの各々カラム幅が揃わなくなるので、
display: none ではなく、visibility:hiddenを適用する。
******************************************************************************/
(function($) {
$.fn.headFixed = function()
{
return this.each(function() {
var $table = $(this).find('table:first');
var $wrapElement =
$('<div>')
.css({'position': 'absolute','top': 0,'left':0,'width': $table.outerWidth(),'overflow':'hidden'})
.height($table.find('thead').outerHeight());
var $wrap =
$table
.clone()
.insertAfter($table)
.wrap($wrapElement)
.css('width','100%')
.find('tbody')
.css({'visiblity': 'hidden'})
.end()
.parent();
$table
.find('thead')
.css({'z-index':10,'visibility': 'hidden'});
$(this).on('scroll',function() {
$wrap.css({'top':$(this).scrollTop()});
});
// ウィンドウのリサイズに追随
$(window).resize(function() {
$wrap.width($table.outerWidth());
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment