Фиксированный заголовок таблицы до верхней части окна при прокрутке, прыжки / пропускают ряд.jquery

StackOverflow https://stackoverflow.com//questions/9637088

Вопрос

Пожалуйста, смотрите My jsfiddle Я создал, чтобы повторить мою проблему. http://jsfiddle.net/motocomdigital/22kfs/3/

В моем проекте я создал таблицу, которая сортируется. Я использовал сортировщик таблиц jQuery Для этого - это очень простой плагин jQuery. Сортировщик таблицы также включен в jsfidde. Если вы нажмете заголовки настольных устройств, вы заметите, что сортирует столбцы таблицы от упущений к возрастанию.

Это нормально, проблема у меня есть ...

на моем живом веб-сайте, стол около 125 рядов высоты. И я хочу избежать популярности таблицы на всех расходах.

Поэтому моя идея состояла в том, чтобы исправить заголовок стола при прокрутке с jQuery, который почти работает. Пожалуйста, смотрите My Widdle . JQuery Я использовал для того, чтобы исправить заголовок к вершине страниц.

Проблема заключается в том, что заголовок таблицы становится фиксированным, таблица сдвигает ряд, и делает его очень глючить.

Может ли кто-нибудь помочь мне удалить глюк и остановить его пропустить ряд, когда она достигает верхней части окна.

действительно ценит любую помощь спасибо.


Смотрите jsfiddle здесь http://jsfiddle.net/motocomdigital/22kfs/3/


<Сильный> jQuery

var $window     = $(window),
    $tableHead  = $(".table-head"),
    offset      = $tableHead.offset();

$window.scroll(function() {
    if ($window.scrollTop() > offset.top) {
        $tableHead.addClass('fixed');
    } else {
        $tableHead.removeClass('fixed');
    }
});
.


<Сильные> CSS

.fixed {
   position: fixed;
   top: 0;
}
.


<Сильные> HTML

<table id="table-sorter" width="400" border="0" cellspacing="0" cellpadding="10">         
    <thead>
            <tr class="table-head">
                <th width="100" height="18" valign="middle">Number</th>
                <th width="100" height="18" valign="middle">First Name</th>
                <th width="100" height="18" valign="middle">Surname</th>
                <th width="100" height="18" valign="middle">System</th>
            </tr>
    </thead>
    <tbody>
            <tr>
                <td>1</td>
                <td>John</td>
                <td>Smith</td>
                <td>Wordpress</td>     
            </tr>

            ... ...

    </tbody>
</table>
.


















Это было полезно?

Решение

Solved your problem. In case you hadn't realised already, the reason it jumps is because you are essentially removing the header row from the table when you make it position fixed, so the rest of the table jumps up to fill the gap.

The solution? Well, it's up for debate. To prove my point, all I've done is add a new temporary header when you make the actual header fixed. This keeps the table in place and allows the header to move down. When you scroll back up, that temporary header then gets removed.

Is this the best way? Not sure, you maybe want to clone the real header as a temporary solution, just in case of graphical glitches. This would also mean that in case of headers with multiple lines (therefore pushing the height down), the effect would be maintained as it's taking an exact clone.

Anyway, on with the code: http://jsfiddle.net/chricholson/22KFS/5/

$("#table-sorter").tablesorter({
 widgets: ['zebra']
});


var $window     = $(window),
    $tableHead  = $(".table-head"),
    offset      = $tableHead.offset();

$window.scroll(function() {


    if ($window.scrollTop() > offset.top) {
        $tableHead.addClass('fixed');
        if ($('#table-sorter thead tr.temp').length <= 0){
            $('#table-sorter thead').append('<tr class="temp"><td>hello</td></tr>');
        }
    } else {
        $tableHead.removeClass('fixed');
        $('tr.temp').remove();
    }


}); 

​ Good luck.

EDIT

Here's the working product using clone() http://jsfiddle.net/chricholson/22KFS/8/

Code:

$("#table-sorter").tablesorter({
     widgets: ['zebra']
});


var $window     = $(window),
    $tableHead  = $(".table-head"),
    offset      = $tableHead.offset();

$window.scroll(function() {


    if ($window.scrollTop() > offset.top) {
        $tableHead.addClass('fixed');
        if ($('#table-sorter thead tr.temp').length <= 0){
            $tableHead.clone().appendTo('#table-sorter thead').removeClass('fixed').addClass('temp');
        }
    } else {
        $tableHead.removeClass('fixed');
        $('tr.temp').remove();
    }


});    ​
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top