Shrink header height by scrollTop value

扶醉桌前 提交于 2019-12-02 16:11:18

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/12350972/shrink-header-height-by-scrolltop-value

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