仅在 div 容器内固定位置元素 [英] Fixed position element inside div container only

查看:27
本文介绍了仅在 div 容器内固定位置元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在容器中有一个固定的块元素.滚动时,固定定位的元素超出了容器.我知道固定元素将根据窗口 vw 定位.但是有什么方法可以确保固定定位的元素只会滚动到容器位置.固定位置元素不应超出容器

问题如下.

https://codepen.io/anon/pen/dKLByX

我尝试使用以下方法解决问题:

if($(window).scrollTop()>1900){$('.fixed-ct').css({'bottom':'200px','top':'auto'});}else if($(document).scrollTop() <=100) {$('.fixed-ct').css({'top':'10px','bottom':'auto'});}别的 {$('.fixed-ct').css({'top':'0px','bottom':'auto'});}

但有时固定容器在末尾,因为底部 200px 它应该在顶部使用 top:0px 滚动并且它应该在容器本身内部.

解决方案

就这样,在 .fixed-ct 中使用 position sticky 并添加 position:relative 到 .main-ct

.main-ct {宽度:1000px;高度:600px;边框:1px 实心 #000;位置:相对;}.fixed-ct {位置:粘性;宽度:100px;高度:20px;背景:红色;顶部:10px;}.like-body {宽度:100%;高度:1300px;}

I have a fixed block element inside a container. On scrolling the fixed positioned element is going beyond the container. I understood fixed element will be positioned according to window vw. But is there any way to make sure fixed positioned element will get scrolled only upto container position. The fixed position element should not go beyond the container

The problem can be seen in the following.

https://codepen.io/anon/pen/dKLByX

I tried to fix the problem using the following:

if($(window).scrollTop()>1900){
    $('.fixed-ct').css({'bottom':'200px','top':'auto'});
}else if($(document).scrollTop() <=100) {
    $('.fixed-ct').css({'top':'10px','bottom':'auto'});
}else {
    $('.fixed-ct').css({'top':'0px','bottom':'auto'});
}

but sometimes the fixed container is at end because of bottom 200px it should be at top using top:0px on scroll and it should be inside the container itself.

解决方案

There you go, use position sticky inside .fixed-ct and add position:relative to .main-ct

.main-ct {
  width: 1000px;
  height:600px;
  border: 1px solid #000;
  position:relative;
}
.fixed-ct {
  position: sticky;
  width:100px;
  height:20px;
  background: red;
  top:10px;
}
.like-body {
  width: 100%;
  height:1300px;
}

<div class="like-body">
  <div class="main-ct">
    <div class="fixed-ct"></div>
  </div>
</div>

这篇关于仅在 div 容器内固定位置元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆