使用jQuery On Scroll切换CSS背景图像

时间:2014-04-10 01:22:00

标签: javascript jquery html css

我试图让一个标题在滚动时变小一点。目前,代码在头大小中涉及的jQuery看起来像这样:

$(function() {
    $('#Header').data('size','big');
});

$(window).scroll(function() {
    if ($(document).scrollTop() > 0) {
        if ($('#Header').data('size') == 'big') {
            $('#Header').data('size', 'small');
            $('#Header').stop().animate({
                height: '60px'
            }, 600);
        }
    } else {
        if ($('#Header').data('size') == 'small') {
            $('#Header').data('size', 'big');
            $('#Header').stop().animate({
                height: '100px'
            }, 600);
        }  
    }
});

它工作得很好,我的标题大小部分缩小了。为了将徽标的大小从大约80 x 80更改为40 x 40(并包括转换),我如何在某种程度上复制这一点?

这是徽标的CSS:

#Logo {
    background: url("images/Logo.png") no-repeat;
    position: absolute;
    top: 8px;
    width: 81px;
    height: 85px;
    z-index: 73;
    -webkit-transition: background-image .5s;
    margin-left: 100px;
}

网站网址为http://www.tremor.yt/Site/Creators.html

1 个答案:

答案 0 :(得分:1)

*已编辑以包含您的完整代码

你的JS:

$(function() {
    $('#Header').data('size','big');
});

$(window).scroll(function() {
    if ($(document).scrollTop() > 0) {
        if ($('#Header').data('size') == 'big') {
            $('#Header').data('size', 'small');
            $('#Header').stop().animate({
                height: '60px'
            }, 600);
            $('#Logo').stop().animate({
                height: '40px',
                width: '40px'
            },600);
        }
    } else {
        if ($('#Header').data('size') == 'small') {
            $('#Header').data('size', 'big');
            $('#Header').stop().animate({
                height: '100px'
            }, 600);
            $('#Logo').stop().animate({
                height: '85px',
                width: '81px'
            },600);
        }  
    }
});

你的css:

#Logo {
    background: url("images/Logo.png") no-repeat;
    background-size: contain;
    position: absolute;
    top: 8px;
    width: 81px;
    height: 85px;
    z-index: 73;
    -webkit-transition: background-image .5s;
    margin-left: 100px;
}

我只是想指出,虽然jquery很容易做到这一点,但有些人(包括我自己)可能会认为最好切换一个css类(类似于'较小的') #Header和#Logo并使用css来调整大小和动画。那么css转换将是:

#Header, #Logo {
    transition: height 0.6s, width 0.6s;
}
相关问题