Fixed div inside scrolling div(修复了滚动 div 内的 div)
问题描述
我需要只在鼠标悬停在滚动条上时修复具有 980px 宽度
和 500px 高度
(class="main") 的网站的主要部分div 的 height 为 1500px
,width 为 100%
(class="container-scroll"),它位于其他 div 中,height 为 500px.
(class="container")
I need to make the main of my site that has 980px width
and 500px height
(class="main") be fixed only when the mouse is over a scrolling div and has a height of 1500px
and a width of 100%
(class="container-scroll"), that is inside other div with height of 500px.
(class="container")
很困惑,对吧?
我做了一个fiddle,我快到了,问题是如果我将main设置为fixed,它会随着页面滚动,而不仅仅是div内部
I made a fiddle, I'm almost there, the problem is that if I set up the main to fixed, it will scroll with the page , not just inside the div
这是我的小提琴:https://jsfiddle.net/8oj0sge4/1/embedded/result/
HTML:
<div id="wrapper">
<div class="container">
<div class="container-scroll">
<div class="main">
</div>
</div>
</div>
</div>
CSS:
#wrapper {
width: 100%;
height: 1500px;
border: 1px solid red;
padding-top: 380px;
}
#wrapper .container {
border: 1px solid green;
width: 100%;
height: 500px;
overflow: scroll;
}
#wrapper .container-scroll {
height: 1500px;
width: 100%;
border: 1px solid yellow;
}
#wrapper .main {
width: 980px;
height: 500px;
background: black;
overflow: scroll;
/*position: fixed;*/
}
推荐答案
如果我理解正确的话,你希望主 div 保持在父 div 的顶部吗?
If I'm understanding this correctly, you want the main div to stay on the top of the parent div?
小提琴:https://jsfiddle.net/8oj0sge4/3/ (完整)
所做的更改:
#wrapper .main
:添加了position:absolute
(固定"到父级)#wrapper .container-scroll
:添加position: relative
(确定要修复"到哪个父级)- 在主 div 中添加了一个 id(为方便起见)
#wrapper .main
: Addedposition:absolute
("fixed" to parent)#wrapper .container-scroll
: Addedposition: relative
(determines what parent to "fix" to)- Added an id to the main div (for convenience)
JavaScript 代码:
JavaScript code:
var main = document.getElementById('main-site');
var maxTop = main.parentNode.scrollHeight-main.offsetHeight; // Make sure we don't go outside the parent
main.parentNode.parentNode.onscroll = function() {
main.style.top = Math.min(this.scrollTop,maxTop) + "px";
}
这篇关于修复了滚动 div 内的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:修复了滚动 div 内的 div


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01