【问题标题】:make an absolute div be positioned off screen with scrolling通过滚动将绝对 div 定位在屏幕外
【发布时间】:2016-07-09 07:26:36
【问题描述】:

我有一个绝对放置的 div,它使用 CSS:

.overlay {
  position:absolute;
  margin:0.5%;
  z-index:100;
}
.topRightOverlay {
  top:0;
  right:0;
}

我的正文和 HTML 都有一个最小高度和宽度。但是,当我将浏览器窗口缩小到最小尺寸以下时,绝对 div 不会粘在最右上角,而是跟随视口进入,然后在我滚动时保持定位(不跟随视口返回)。

我怎样才能确保这个 div 保持在 HTML/body 的右上角,即使这意味着在滚动到屏幕之前离开屏幕?

这是 HTML 结构:

<html lang="en">
  <body>
    <form runat="server">
      <div class="overlay topRightOverlay">
        <!-- overlay content -->
      </div>
      <!-- content placeholder for content pages -->
    </form>
  </body>
</html>

还有 HTML、Body CSS:

body, html {
    height: 100%;
    min-height:600px;
    min-width:800px;
    overflow:hidden;
}
html {overflow:auto;}

body,
html {
  height: 100%;
  min-height: 600px;
  min-width: 800px;
  overflow: hidden;
}
html {
  overflow: auto;
}
form {
  height: 100%;
}
.overlay {
  position: absolute;
  margin: 0.5%;
  z-index: 100;
}
.topRightOverlay {
  top: 0;
  right: 0;
}
<html lang="en">

<body>
  <form runat="server">
    <div class="overlay topRightOverlay nonInteractive">
      This is an overlay
    </div>
    <!-- content placeholder for content pages -->
  </form>
</body>

</html>

【问题讨论】:

  • 你能把你正在使用的html结构添加到这篇文章中吗?

标签: html css scroll absolute


【解决方案1】:

如果我理解正确的话:

您必须提供正文 position: relative 并添加一些 javascript 以保留 absolute 元素的 offset()

你自己看看

$(document).ready(function(){
var posY;
document.onscroll = function(){
	posY = 100 + $(window).scrollTop();//locate needed Y position 
	$("#absDiv").offset({top: posY}); //Apply position
};
})
body{
  margin:0;
  padding:0;
  width: 100%;
  position: relative;
}

section {
  height: 1500px;
  width:100%;
  background-color: #2ecc71;
}

#absDiv {
  width: 80px;
  padding: 5px;
  line-height: 17px;
  position:absolute;
  right:0;
  top:100px;
  background-color: #d35400;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div id="absDiv">
      I'm pretty fixed to this place...
    </div>
    <section>
    </section>
</body>

希望我能帮到你:)

干杯,

唤起

【讨论】:

    【解决方案2】:

    在 .topRightOverlay 类中使​​用绝对位置。 希望能解决问题

    【讨论】:

    • 我给浮动 div 这两个类。我把它分开以避免重复。我有 topLeftOverlay、bottomRightOverlay 等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2018-12-05
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多