简体   繁体   中英

To move/fix a DIV element to top upon scrolling the page

Please find below a sample HTML code that fixes the position of a DIV element. Now, I need to be able to move the "setupBar" to (0, 0) position (or appropriate position based on where the scroll position is) once I start scrolling, and then just freeze it.

<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: I am looking for a JS solution that can move the DIV up or down depending on the current scroll position (not a CSS fix) :)

I think, You want this http://jsfiddle.net/Kr4TJ/4/

I set setupBar position to absolute to make it naturally fallow mainBar when document scrolled. When mainBar is not visible anymore, the position of setupBar is set to fixed and top distance set to 0px . If mainBar is visible again, then setupBar position change back to absolute and set style.top="" which brings back to natural position.

Try this solution

<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>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM