Javascript 如何让一个 DIV 始终漂浮在屏幕右上角?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4236151/
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
How to make a DIV always float on the screen in top right corner?
提问by akanevsky
How do I make a DIV always float on the screen's top right corner, so that even when I scroll the page down, the DIV still shows up in the same fixed location? Thanks.
如何使 DIV 始终浮动在屏幕的右上角,以便即使向下滚动页面,DIV 仍会显示在相同的固定位置?谢谢。
回答by BoltClock
Use position: fixed
, and anchor it to the top
and right
sides of the page:
使用position: fixed
, 并将其锚定到页面的top
和right
两侧:
#fixed-div {
position: fixed;
top: 1em;
right: 1em;
}
IE6 does not support position: fixed
, however. If you need this functionality in IE6, this purely-CSS solutionseems to do the trick. You'll need a wrapper <div>
to contain some of the styles for it to work, as seen in the stylesheet.
position: fixed
但是,IE6 不支持。如果您在 IE6 中需要此功能,这个纯 CSS 解决方案似乎可以解决问题。您需要一个包装器<div>
来包含一些样式才能使其工作,如样式表中所示。
回答by Alex
Use position:fixed
, as previously stated, IE6 doesn't recognize position:fixed
, but with some css magic you can get IE6 to behave:
使用position:fixed
,如前所述,IE6 无法识别position:fixed
,但通过一些 css 魔法,您可以让 IE6 表现得像:
html, body {
height: 100%;
overflow:auto;
}
body #fixedElement {
position:fixed !important;
position: absolute; /*ie6 */
bottom: 0;
}
The !important
flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement
use position:fixed
in all browsers but IE, and in IE
, position:absolute
will take effect with bottom:0
. This will simulate position:fixed
for IE6
该!important
标志使您不必为 IE 使用条件注释。这将#fixedElement
使用position:fixed
在所有的浏览器,但IE浏览器,并IE
,position:absolute
将采取与效果bottom:0
。这将模拟position:fixed
IE6