Skip to content

Instantly share code, notes, and snippets.

@egorvinogradov
Last active December 14, 2015 13:08
Show Gist options
  • Save egorvinogradov/5091100 to your computer and use it in GitHub Desktop.
Save egorvinogradov/5091100 to your computer and use it in GitHub Desktop.
jQuery-плагин для широких таблиц (шире экрана), при использовании которого первый столбец таблицы с названиями полей начинает двигаться вслед за горизонтальным скролом.
.fixed-captions {
display: none;
position: absolute;
background: #CDCDCD;
border-spacing: 1px;
margin-top: 1px;
box-shadow: 5px 0 6px rgba(0,0,0,.2);
}
.fixed-captions td {
padding: 0 7px;
background: #fff;
}
.fixed-captions_visible {
display: block;
}
.fixed-captions-container {
position: relative;
}
.fixed-captions-wrapper {
overflow-x: scroll;
}
/**
* @example: $('.data_table').fixCaptions();
*/
$.fn.extend({
fixCaptions: function(){
function fixCaptions(i, el){
var table = $(el);
var tableCaptions = cloneTableCaptions(table);
var isScrolling = false;
table
.wrap('<div class="fixed-captions-wrapper"></div>')
.parent()
.on('scroll', onTableScroll)
.wrap('<div class="fixed-captions-container"></div>')
.parent()
.prepend(tableCaptions);
var tableContainer = $('.fixed-captions-container');
var tableWrapper = $('.fixed-captions-wrapper');
function cloneTableCaptions(table){
var captions = $('<table class="fixed-captions"></table>');
var trs = table.clone().find('tr')
.map(function(i, el){
var tr = $(el);
var height = table.find('tr').eq(i).height();
return $('<tr></tr>').append( tr.find('td').first().height(height) )
})
.each(function(i, tr){
captions.append(tr);
});
return captions;
};
function onTableScroll(e){
if ( isScrolling ) {
return;
}
isScrolling = true;
setTimeout(function(){
var shift = tableWrapper.scrollLeft();
if ( shift > 50 ) {
tableCaptions.addClass('fixed-captions_visible');
}
else {
tableCaptions.removeClass('fixed-captions_visible');
}
isScrolling = false;
}, 100);
};
};
this.each(fixCaptions);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment