我正在尝试制作一个在滚动时稍微变小的页眉。目前,对于涉及 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;
}
最佳答案
*编辑以包含您的完整代码
你的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/