【问题标题】:To move/fix a DIV element to top upon scrolling the page在滚动页面时将 DIV 元素移动/固定到顶部
【发布时间】:2012-01-09 12:06:21
【问题描述】:

请在下面找到固定 DIV 元素位置的示例 HTML 代码。现在,一旦我开始滚动,我需要能够将“setupBar”移动到 (0, 0) 位置(或基于滚动位置的适当位置),然后冻结它。

<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:我正在寻找一种可以根据当前滚动位置向上或向下移动 DIV 的 JS 解决方案(不是 CSS 修复):)

【问题讨论】:

  • 我很好奇你为什么不只是想使用一个位置:固定; css 样式定义要这样做吗?这似乎是一个比 js 更清洁的解决方案。
  • CSS 更适合这个目的

标签: javascript css html


【解决方案1】:

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

我将setupBar 的位置设置为absolute 以使其在文档滚动时自然地闲置mainBar。当mainBar 不再可见时,setupBar 的位置设置为fixedtop 距离设置为0px。如果mainBar 再次可见,则将setupBar 位置更改回absolute 并设置style.top="" 以恢复自然位置。

【讨论】:

    【解决方案2】:

    试试这个解决方案

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多