我有一个粘性菜单栏,当它滚动到我放置 anchor 的标题下方时,它就会开始粘住。
它运行良好,但我希望在它开始“粘住”后在其左侧显示一个图像。我在 newyorker.com 上看到了同样的效果。
我该怎么做?
这是我的代码,让它坚持下去:
$(window).scroll(function(e) {
var scroller_anchor = $(".scroller_anchor").offset().top;
if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed')
{
$('.scroller').css({
'position': 'fixed',
'top': '0px'
});
$('.scroller_anchor').css('height', '50px');
}
else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative')
{
$('.scroller_anchor').css('height', '0px');
$('.scroller').css({
'position': 'relative'
});
}
});
最佳答案
让 CSS 为您做这件事.. 只需在“粘贴”时将类 showed
添加到图像中,然后在不“粘贴”时将其删除
CSS
.home_image{
display: none;
float: left;
height: 50px;
width: 50px;
}
.home_image.showed{
display: block;
}
JavaScript
$(window).scroll(function(e) {
var scroller_anchor = $(".scroller_anchor").offset().top;
if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed')
{
$('.scroller').css({
'position': 'fixed',
'top': '0px'
});
$('.home_image').addClass('showed');
$('.scroller_anchor').css('height', '50px');
}
else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative')
{
$('.scroller_anchor').css('height', '0px');
$('.scroller').css({
'position': 'relative'
});
$('.home_image.showed').removeClass('showed');
}
});
另一种不加类的方式:
CSS
.home_image{
display: none;
float: left;
height: 50px;
width: 50px;
}
JavaScript
$(window).scroll(function(e) {
var scroller_anchor = $(".scroller_anchor").offset().top;
if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed')
{
$('.scroller').css({
'position': 'fixed',
'top': '0px'
});
$('.home_image').css({
'display': 'block'
});
$('.scroller_anchor').css('height', '50px');
}
else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative')
{
$('.scroller_anchor').css('height', '0px');
$('.scroller').css({
'position': 'relative'
});
$('.home_image').css({
'display': 'none'
});
}
});
关于jquery - 粘性菜单 - 如何让图像在 "sticks"时立即显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528536/