Fixed header inside scrolling block

倾然丶 夕夏残阳落幕 提交于 2019-12-11 11:49:55

问题


I'm trying to create a block which may or may not have a scrollbar, with a header that does not scroll. The trick is that the width of the header should be affected by the presence of a scrollbar.

I'm worried that this is one of those CSS use cases which should be trivial, but might, in fact, be impossible. Anyone willing to prove me wrong?


回答1:


Here are a few pointers

http://davidchambersdesign.com/css-fixed-position-headers/

and there involve tables with fixed header and scrolling body

  1. http://imar.spaanjaars.com/357/a-scrollable-table-with-a-fixed-header
  2. http://anaturb.net/csstips/sheader.htm



回答2:


You cannot do this with CSS alone. We must use javaScript. With jQuery you can do the following

var cw = $('#container').innerWidth(),
    cs = $('#container').scrollTop();

    $('#header').css({
        'width': cw + "px"
    });

    $('#container').scroll(function() {
        $('#header').css({
            'top': $('#container').scrollTop(),
        })
    })

Check working example at http://jsfiddle.net/VswxL/2/




回答3:


I haven't figured out how to do this with CSS alone. So, here's a solution which uses JavaScript (here, jQuery), but only runs when he content changes. If the size of your wrapper depends on the size of the window, you may also need to run it on resize. Here's the heart of it:

$.fn.fitTo = function(target){
    var $el = $(this);
    $(target).bind('refit', function(){
        $el.width(this.clientWidth);
    });
}

Call $header.fitTo($content) to bind the header to a custom refit event on the element with the content. Now, whenever the content changes such that a scroll bar may have appeared or disappeared, do…

$content.trigger('refit');

…and the width of the header is reset to the clientWidth of the element containing content. The header must be outside the scrolling element.

Working example



来源:https://stackoverflow.com/questions/5228098/fixed-header-inside-scrolling-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!