通过scrollTop值缩小标题高度 [英] Shrink header height by scrollTop value

查看:129
本文介绍了通过scrollTop值缩小标题高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Howdey!

简单的问题:我有一个固定头文件,高度根据窗口缩小scrollTop -value为其高度的一半。



到目前为止:

HTML

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

CSS
< pre $ body {padding-top:200%} / *不是真的需要* /

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

颜色:#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();

这是 小提琴



到目前为止效果很好。但是,如果用户向下滚动,例如

任何想法如何解决它?

解决方案

if语句没有问题。当初始滚动状态位于底部时,您需要添加一个else语句。例如:

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


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

这篇关于通过scrollTop值缩小标题高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆