修复了滚动div内的div [英] Fixed div inside scrolling div
问题描述
我需要使我的网站的主要内容 980px宽度
和 500px高度
(class =main )仅当鼠标位于滚动div并且高度为1500px
且宽度为100%
(class =container-scroll),在其他div中,高度为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")
相当困惑,对吗?
我做了一个小提琴,我差不多了,问题是如果我把主要设置为固定,它将滚动页面,而不仅仅是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/ ( full )
所做的更改:
-
#wrapper .main
:已添加位置:绝对
(固定为父级) -
#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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!