javascript - 在滚动时使用 jQuery 切换 CSS 背景图像

标签 javascript jquery html css

我正在尝试制作一个在滚动时稍微变小的页眉。目前,对于涉及 header 大小的 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);
        }  
    }
});

它工作得很好,我减少了页眉大小部分。我怎样才能稍微复制它以将 Logo 的大小从大约 80 x 80 更改为 40 x 40(并包括过渡)?

这是 Logo 的 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;
}

站点 URL 是 http://www.tremor.yt/Site/Creators.html

最佳答案

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

你的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 做得很好而且很容易,但有些人(包括我自己)可能认为最好在 #Header 和 #Logo 上切换一个 css 类(类似于“更小”)和使用 css 来调整大小和动画。然后 css 转换将是:

#Header, #Logo {
    transition: height 0.6s, width 0.6s;
}

关于javascript - 在滚动时使用 jQuery 切换 CSS 背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976951/

相关文章:

javascript - 如何使用 javascript 将自定义类名添加到 Highcharts 中的刻度定位器

javascript - 有没有正确的方法来处理 require.js 的 DOM 就绪事件? (不,domReady 插件不起作用)

html - 在不复制源代码块的情况下,将非连续内容 block 扩展到XL屏幕上的侧边栏

jquery-鼠标移动 : how to prevent div to stop follow the mouse

javascript - Node js - 加载循环

javascript - 如何使用 `localStorage` 来存储整个页面?

javascript - 如何使用 array.fill 创建对象数组?

javascript - 如何从具有特定类名的特定标签获取文本值?

javascript - 在重定向之前将有关单击链接的信息发送到服务器

html - 显示 HTML5 进度条的内部文本?未实现的技术原因?