javascript 将 div 粘贴到浏览器窗口的底部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31942227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:37:24  来源:igfitidea点击:

Stick div to bottom of browser window

javascriptjqueryhtmlcss

提问by user715564

I have a div that I would like to stick to the bottom of the browser window (the actual browser window not the page). The div needs to stay at the bottom of the browser window while the user scrolls.

我有一个 div,我想贴在浏览器窗口的底部(实际的浏览器窗口而不是页面)。当用户滚动时,div 需要停留在浏览器窗口的底部。

Right now, the div will stick to the bottom of the window on the first initial scroll but it will not re-position each time there is a new scroll. Here is what I have for my jQuery:

现在,div 将在第一次初始滚动时粘在窗口的底部,但不会在每次有新滚动时重新定位。这是我的 jQuery 的内容:

$(window).scroll(function () { 
    var bHeight = $(window).height();
    $('.test').css({
        top: bHeight - 77 + 'px'
    });
});

Here is a jsfiddle http://jsfiddle.net/3ecx7zp9/1/

这是一个 jsfiddle http://jsfiddle.net/3ecx7zp9/1/

回答by Rohit Kumar

This can simply be done in CSS. Remove all your JavaScript, and do the following:

这可以简单地在 CSS 中完成。删除所有 JavaScript,然后执行以下操作:

position: fixed;
bottom: 77px;

Fiddle

小提琴

回答by DGS

Have you considered using a fixed position div? set position: fixedand bottom: 77px

您是否考虑过使用固定位置的 div?设置position: fixedbottom: 77px

However if you must use a jQuery solution change your code to this

但是,如果您必须使用 jQuery 解决方案,请将代码更改为此

$(window).scroll(function () { 
    var bHeight = $(window).height();
    var offset = $(window).scrollTop();
    $('.test').css({
        top: bHeight + offset - 77 + 'px'
    });
});

http://jsfiddle.net/3ecx7zp9/6/

http://jsfiddle.net/3ecx7zp9/6/

That takes into account how far you have scrolled and will set the position of the div accordingly

这考虑到您滚动了多远,并将相应地设置 div 的位置

回答by Kyrbi

In your CSS use position: fixed;instead of position: absolute;.

在您的 CSS 中使用position: fixed;而不是position: absolute;.

http://jsfiddle.net/3ecx7zp9/4/

http://jsfiddle.net/3ecx7zp9/4/

回答by Kleioz

Do you want to use position: fixed;?

你想用position: fixed;吗?

https://jsfiddle.net/js7tadve/1/

https://jsfiddle.net/js7tadve/1/

回答by B Karthik Kumar

This is precisely what position: fixed was designed for:

这正是 position: fixed 的设计目的:

#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}

Here's the fiddle: http://jsfiddle.net/uw8f9/

这是小提琴:http: //jsfiddle.net/uw8f9/

回答by MoLow

here you go:

干得好:

 <div class="test" style="position: fixed; width: 100%; height: 77px; background-color: #333;left:0;bottom:0"></div>

回答by Steevan

Check if the below link will work with you.

检查以下链接是否适用于您。

Fiddle

小提琴

#footer {
position: fixed;
bottom: 0;
height: 77px;
width: 100%;
background-color: #333;
}