11 901 Скрипты / Layout

Липкий header


Прикрепляемый хедер к верху страницы при её прокручивании. Реализовано на jQuery.

HTML

<div id="container">
    
    <h2>Липкий хедер на jQuery</h2>
    
    <div id="header">
        <!-- липкий хедер -->
    </div>
    
    <div id="content">
        <!-- контент -->
    </div>
    
</div><!-- /container -->

CSS

Стиль для демки:

#container {
    width: 960px;
    margin: 5em auto;
    text-align: left;
}
 
#header{
    width:958px;
    border:1px solid #ebebee;
    border-bottom:3px solid #ddd;
    background-image: -webkit-linear-gradient(top, #fff, #ebebee);
    background-image:    -moz-linear-gradient(top, #fff, #ebebee);
    background-image:     -ms-linear-gradient(top, #fff, #ebebee);
    background-image:      -o-linear-gradient(top, #fff, #ebebee);
    background-image:         linear-gradient(top, #fff, #ebebee);
}
 
#content{
    padding:10px;
    border:1px solid #e8e8e8;
    border-bottom:3px solid #e8e8e8;
    border-top: none;
    border-radius:4px;
    background:#fcfcfc;
    margin:20px 0;
}

JS

Подключаем jQuery и сам код прикрепления:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/jаvascript"></script>
<script type="text/jаvascript">
    $(document).ready(function(){
        var HeaderTop = $('#header').offset().top;
        
        $(window).scroll(function(){
                if( $(window).scrollTop() > HeaderTop ) {
                        $('#header').css({position: 'fixed', top: '0px'});
                } else {
                        $('#header').css({position: 'static'});
                }
        });
    });
</script>
Скачать 2264Загрузок 6,64 Kb
Демо

Комментарии

  • Facebook
  • Вконтакте

Похожие статьи