我创建了一个粘性栏以留在窗口底部。当用户向下滚动到页面底部时,相同的栏将保持固定,直到页脚显示,然后暂时移除其固定位置以停留在页脚上方,直到用户向上滚动并再次保持固定。
我只想在页面宽度超过 680 像素时发生。其下的任何内容都会使粘滞条保持在默认位置(CSS:position:inherit)。
这是网站:http://ttd.firefly-digital.co.uk
它按预期工作。但是,当我在 Mac 的 Chrome 上测试时,它触发了我的 CPU 风扇,这表明这不是很有效,而且我的 JavaScript 技能有限,想知道是否有更简洁的方法来实现这一点?
这是当前的js代码:
$(window).scroll(function(event) {
var scroll = $(this).scrollTop();
var docHeight = $(document).height();
var windowHeight = $(window).height();
var footerHeight = $('.footer').height();
if(docHeight - (windowHeight + scroll) < footerHeight) {
$('.contact-bar').css({
bottom: footerHeight - (docHeight - (windowHeight + scroll))
});
} else {
$('.contact-bar').css({
bottom: 0
});
}
});
var windowWidth = $(window).width();
$(window).resize(function() {
windowWidth = $(window).width();
if(windowWidth > 680) {
$('.contact-bar').css({
position: "fixed"
});
} else {
$('.contact-bar').css({
position: "inherit"
});
}
});
CSS代码
.contact-bar {
background: $contact-bar;
width: 100%;
height: 40px;
text-align: center;
position: fixed;
bottom: 0;
z-index: 10;
}
最佳答案
你可以反过来做。使没有固定位置的栏位于页脚上方,没有任何 JavaScript(包括媒体查询)。比添加一个带有 position:fixed 和 bottom:0 的固定类将被相应地添加。像这样:
.contact-bar.fixed { position:fixed; bottom:0; }
将触发此操作的 jquery 代码如下:
$(window).scroll(function (event) {
var windowTop = $(this).scrollTop();
if (windowTop >= $(".footer").offset().top) {
$(".contact-bar").addClass("fixed");
} else {
$(".contact-bar").removeClass("fixed");
}
});
然后添加几行,上面的代码只有在窗口宽度大于 680 时才会触发,无论是使用 jquery 还是纯 javascript。例如:
if ($(window).width() < 960) { // above function }
请注意我还没有测试过这个,所以如果它不起作用请发表评论。信用:Preventing element from displaying on top of footer when using position:fixed
关于javascript - 在窗口底部固定 div 但保持在页脚上方并在页面宽度上触发的更简洁的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27985099/