문제

Howdey!

Simple problem: I've a fixed header, the height shrinks down based on the window scrollTop-value to the half of its height.

What I have so far:

HTML

<div id="header">
    <img src="http://yckart.com/ph?text=scroll down" alt>
</div>

CSS

body{padding-top:200%} /* not really needed */

#header {
    position:fixed;
    top:0;
    left:0;
    right:0;
    height:200px;

    color:#eee;
    background:#222
}

#header img {height:100%; width:auto}

JS

var header = $('#header'),
    headerH = header.height();

$(window).scroll(function() {
    if ($(this).scrollTop() <= headerH / 2) {
        header.css({
            height: -($(this).scrollTop() - headerH)
        });
    }
}).scroll();

Here's a fiddle.

Works well so far. However, if the user scrolls down e.g. to the bottom and reloads the page, the if statement doesn't work.

Any ideas how to fix it?

도움이 되었습니까?

해결책

Nothing wrong with the if statement. You need to add an else statement for when the initial scroll state is at the bottom. E.g.:

    var header = $('#header'),
    headerH = header.height();

$(window).scroll(function() {
    if ($(this).scrollTop() <= headerH / 2) {
        header.css({
            height: -($(this).scrollTop() - headerH)
        });
    } else {
      header.css({
            height: headerH / 2
        });
    }
}).scroll();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top