Скрыть заголовок при прокрутке, контент появляется над ним

Я хочу создать «фиксированный» заголовок с autoHeight, и когда вы прокручиваете содержимое, оно появляется.

Вот пример: http://clapat.ro/berger/about.html

По сути, это домашняя/вступительная секция (id #hero), которая имеет автовысоту и использует эффект параллакса, при прокрутке кажется, что контент появляется над ним.

Это то, что я нашел, просматривая элемент проверки и исходный код:

Заголовок имеет autoHeight (~ 500px по умолчанию, 321px при использовании элемента проверки), получает увеличенное верхнее поле и уменьшенную непрозрачность при прокрутке:

height: 321.3px;
top: 400px;
opacity: -0.246105919003115;

Вот некоторые функции, которые я нашел:

function HeroHeight() {
    if( $('#hero').length > 0 ){

        if ($('#hero').hasClass('hero-big')) {
            var heights = window.innerHeight;
            document.getElementById("hero").style.height = heights * 0.85 + "px";
        } else if ($('#hero').hasClass('hero-small')) {
            var heights = window.innerHeight;
            document.getElementById("hero").style.height = heights * 0.40 + "px";               
        } else  {           
            var heights = window.innerHeight;
            document.getElementById("hero").style.height = heights + "px";
        } 

    }

и код, отвечающий за эффект параллакса

    function HeroParallax() {

    var page_title = $('body');
        var block_intro = page_title.find('#hero');
        if( block_intro.length > 0 ) var block_intro_top = block_intro.offset().top;    
    $( window ).scroll(function() {
        var current_top = $(document).scrollTop(); 
        var hero_height = $('#hero').height();
        if( $('#hero').hasClass('parallax-hero')){            
            block_intro.css('top', (current_top*0.5));          
        }
        if( $('#hero').hasClass('static-hero')){              
            block_intro.css('top', (current_top*1));            
        }
        if( $('#hero').hasClass('opacity-hero')){                
            block_intro.css('opacity', (1 - current_top/hero_height*1));
        }
    });

}

И вот простой эффект, который я нашел, пока гуглил

http://jsfiddle.net/EWefL/

Этот эффект CSS слишком прост, и, поскольку у меня нет опыта работы с JS/jQuery, мне бы не помешала помощь.

Мои вопросы: - Как я могу сделать эту вещь autoHeight? - Как увеличить верхнее поле и уменьшить непрозрачность заголовка при прокрутке?

Большое спасибо, любая помощь будет высоко оценена.


person sandcode    schedule 11.01.2015    source источник


Ответы (2)


Вы можете использовать функцию scroll и изменить ее height, когда scroll станет больше определенной суммы FIDDLE.

$(window).scroll(function(){
    if ($(window).scrollTop() > 20){
        $('header').height('60px');
        $('header').css('z-index' , '300');
    }
    else{
         $('header').height('100px');
        $('header').css('z-index' , '100');
    }
});
body {
    padding:0;
    margin:0;
}
header {
    background:#cff;
    height:100px;
    position:fixed;
    right:0;
    left:0;
    z-index:100;
}
section {
    background: #579;
    height:600px;
    top:100px;
    position:relative;
    z-index:200;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<header><a href="/">Working header link</a>
</header>
<section>Section</section>

person Akshay    schedule 11.01.2015
comment
Это не совсем то, что я ищу, но большое спасибо за ваш ответ! :) - person sandcode; 11.01.2015
comment
Ну, я бы хотел, чтобы заголовок постоянно увеличивал верхнее поле, уменьшал непрозрачность и имел autoHeight. В вашем коде он просто изменит свою высоту один раз. - person sandcode; 11.01.2015

Итак, я нашел решение.

http://codyhouse.co/gem/pull-out-intro-effect/

Я использовал этот фрагмент, избавился от эффекта масштабирования и использовал только непрозрачность.

Вот отредактированный javascript, если кто-то еще его ищет:

jQuery(document).ready(function($){
var introSection = $('#cd-intro-background'),
    introSectionHeight = introSection.height(),
    //change scaleSpeed if you want to change the speed of the scale effect
    scaleSpeed = 0.3,
    //change opacitySpeed if you want to change the speed of opacity reduction effect
    opacitySpeed = 1; 

//update this value if you change this breakpoint in the style.css file (or _layout.scss if you use SASS)
var MQ = 1170;

triggerAnimation();
$(window).on('resize', function(){
    triggerAnimation();
});

//bind the scale event to window scroll if window width > $MQ (unbind it otherwise)
function triggerAnimation(){
        $(window).on('scroll', function(){
            //The window.requestAnimationFrame() method tells the browser that you wish to perform an animation- the browser can optimize it so animations will be smoother
            window.requestAnimationFrame(animateIntro);
        });
}
//assign a scale transformation to the introSection element and reduce its opacity
function animateIntro () {
    var scrollPercentage = ($(window).scrollTop()/introSectionHeight).toFixed(5);
    //check if the introSection is still visible
    if( $(window).scrollTop() < introSectionHeight) {
        introSection.css({
            'opacity': 1 - scrollPercentage*opacitySpeed
        });
    }
}

});
person sandcode    schedule 11.01.2015