2012-01-09 137 views
0

请在下面找到修复DIV元素位置的示例HTML代码。现在,我需要能够在开始滚动时将“setupBar”移动到(0,0)位置(或基于滚动位置的位置),然后将其冻结。在滚动页面时移动/修复DIV元素顶部

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii"> 
</head> 
<body> 
<div id="mainBar" style="height:20px; border:1px solid red"></div> 
<div id="setupBar" style="position:fixed; border:1px solid blue; height:20px; width:100%"></div> 
<div style="height:1500px; background-color:#CCCCCC"></div> 
</body> 
</html> 

PS:我在寻找一个JS的解决方案,可以移动DIV向上或向下取决于当前的滚动位置(不是CSS修复):)

+0

我很好奇你为什么不想只用一个位置:fixed; CSS样式定义来做到这一点?这似乎是一个比js更清洁的解决方案。 – Evert 2012-01-09 12:09:16

+0

重复:http://stackoverflow.com/q/7735002/681807 – 2012-01-09 12:09:19

+0

CSS是更好的这个目的 – Bernat 2012-01-09 12:37:17

回答

1

我认为,你要想这http://jsfiddle.net/Kr4TJ/4/

我设置setupBar位置absolute,使其自然休耕mainBar当文档滚动。当mainBar不再可见时,setupBar的位置设置为fixedtop设置为0px的距离。如果mainBar再次可见,那么setupBar的位置变回absolute并且设置style.top="",这回到自然位置。

+0

是的,谢谢:) – user1018482 2012-01-10 02:59:30

+0

好东西...不得不调整一下.... – Grim 2016-06-14 02:10:02

0

尝试这种解决方案

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii"> 
<script type="text/javascript"> 
function $(obj) 
{ 
    return document.getElementById(obj); 
} 
function fixSetupBar() 
{ 
    $("setupBar").style.top=(document.body.scrollTop)+"px"; 
    $("setupBar").style.left=(document.body.scrollLeft)+"px"; 
} 
</script> 
</head> 
<body onscroll="fixSetupBar()"> 
<div id="mainBar" style="height:20px; border:1px solid red"></div> 
<div id="setupBar" style="position:absolute;top:0px;left:0px;border:1px solid blue; height:20px; width:100%"></div> 
<div style="height:1500px; background-color:#CCCCCC"></div> 
</body> 
</html> 

希望这有助于。