【问题标题】:Position div at the top of screen after scrolling滚动后将 div 置于屏幕顶部
【发布时间】:2017-05-12 03:22:15
【问题描述】:

我正在使用 angular 2,但这个问题主要是关于 css(我使用的是 bootstrap 3)。我有 2 个 div(leftDiv 和 rightDiv),如下所示:

<div class="row">

 <div *ngFor="let address of addresses">
  <div class="card" id="leftDiv">
   <h5 class="card-text">{{address.name}}</h5>
   <h5 class="card-text">{{address.street}}</h5>
   <h5 class="card-text">{{address.city}}</h5>
  </div>
 </div>

 <!-- bunch of code -->

 <div class="col-md-6" id="rightDiv">
  <!-- should appear at the top of current view -->
 </div>

</div>

所以,左侧有一堆地址(leftDiv)。 rightDiv 仅在单击按钮时出现,一次也仅出现 1 个。目前发生的情况是,rightDiv 出现在页面顶部(因此,如果您向下滚动得足够远,您甚至都看不到它)。它应该做的是出现在当前视图的顶部。

position: fixed;

这样做,但随后它粘在屏幕顶部,这是我不想要的(我应该只是出现并留在那里)。 我还尝试将 leftDiv 和 rightDiv 的位置设置为相对和绝对,但这似乎只有在一个是另一个的父级时才有效(这在我的情况下是不可能的)。

我们将不胜感激。

解决方案:

document.getElementById('rightDiv').style.top = 
document.body.scrollTop.toString()+'px';

(见最佳答案)

【问题讨论】:

    标签: html css angular angular-ui-bootstrap


    【解决方案1】:

    这段 css 代码将使 div 贴在屏幕顶部

    位置:固定;上:0px;右:0px;左:0px;

    【讨论】:

    • 这正是我想要阻止的。它应该只出现在屏幕顶部,但不要粘在上面......
    • 那你一定要试试这个
    • 宽度:100%;位置:绝对;顶部:0px;高度:20px;
    【解决方案2】:

    这可能值得研究。 jquery how to get the page's current screen top position?

    然后在您的 CSS 中,我会将位置设置为绝对位置,如下所示:

    position: absolute;
    

    我假设您的按钮已经有一个 clickhandler(显示 rightDiv)。所以在这里你可以添加:

    $('#rightDiv').prop('top',$('#html').offset().top*-1);
    

    (时间 -1 非常重要,因为偏移量将为负数)。 上面提到的代码可能不会马上工作,我不是 CSS 大师,但这就是我过去解决此类问题的方式。

    【讨论】:

    • 谢谢,正是我想要的!我用 document.getElementById('rightDiv').style.top = document.body.scrollTop.toString()+'px';这就像一个魅力
    【解决方案3】:
    enter code here
    

    <table>
     <tr>
      <td style="width:100px; height:500px; background:#00aa00">
        foo
      </td>
      <td style="float:right">
        bar
      </td>
    </tr>
       </table>

    应该让它保持在我们的屏幕上,无论你向下滚动多远

    或者如果您希望右侧出现在您当前滚动到的任何位置,请检查并使用它来设置 margin-top:Determine distance from the top of a div to top of window with javascript

    【讨论】:

    • 这与“Shubham Sharma”的解决方案完全相同,这在我的情况下不起作用,因为我希望它粘在顶部屏幕上......
    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多