javascript - 滚动时不能将一个 div 粘在另一个下面

标签 javascript html css sticky

我有一个 div 在另一个下面。我希望他们在滚动时将一个放在页面顶部的另一个下面。 我的代码看起来像这样-

function sticky_relocate() {
  var window_top = $(window).scrollTop();
  var div_top = $('#sticky-anchor').offset().top;
  if (window_top > div_top) {
    $('#sticky').addClass('stick');
$('#sticky2').addClass('stick');
  } else {
    $('#sticky').removeClass('stick');
$('#sticky2').removeClass('stick');
  }
}

$(function() {
  $(window).scroll(sticky_relocate);
  sticky_relocate();
});
#sticky {
  padding: 0.5ex;
  width: 600px;
  background-color: #333;
  color: #fff;
  font-size: 2em;
  border-radius: 0.5ex;
}
  #sticky2 {
  padding: 0.5ex;
  width: 600px;
  background-color: #333;
  color: #fff;
  font-size: 2em;
  border-radius: 0.5ex;
}

#sticky.stick {
  position: fixed;
  top: 0;
  z-index: 10000;
  border-radius: 0 0 0.5em 0.5em;
}
#sticky2.stick {
  position: fixed;
  top: 0;
  z-index: 10000;
  border-radius: 0 0 0.5em 0.5em;
}
<div id="sticky-anchor"></div>
<div id="sticky">This will stay at top of page</div>
<div id="sticky2">This will stay at top of page 2</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

但在 UI 中,div 相互重叠。 我想要一个在另一个下面。 我有 2 个单独的 div

我的 codepen . 我希望第二个贴在第一个下面。

最佳答案

把你的id改成class,因为你不能重复同一个id名字

<div class="sticky">This will stay at top of page</div>
<div class="sticky">This will stay at top of page 2</div>

.sticky {
  padding: 0.5ex;
  width: 600px;
  background-color: #333;
  color: #fff;
  font-size: 2em;
  border-radius: 0.5ex;
}

.sticky.stick {
  position: fixed;
  top: 0;
  z-index: 10000;
  border-radius: 0 0 0.5em 0.5em;
}

or By default div come one below one , So please try this

    #sticky{
        margin-left:auto;
        margin-right:auto;
        height:auto; 
        width:auto;
    }
    #inner1{
      float:left; 
    }
    #inner2{
      float:left; 
      clear: left;
    }
    </style>

    HTML:

    <div id="sticky">
        <div id="inner1">inner1</div>
        <div id="inner2">inner2</div>
    </div>

关于javascript - 滚动时不能将一个 div 粘在另一个下面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54453277/

相关文章:

javascript - 如何同时使用ajax和普通POST提交表单?

css - 使用 CSS 选择第一个后代

javascript - JS函数通过文件上传更改页面上的图像

javascript - 最后两个字段集之间的奇怪差距

javascript - 引用未定义 react

javascript - 从数组中选择随机元素时如何获得平衡输出?

javascript - 访问 HTML5 音频响应 header

html - 页面调整大小时的 Bootstrap 3.0 导航

html - 带有 float 元素的 div 内的垂直对齐问题

html - 将背景添加到一行文本的第一个字母。如何?