【问题标题】:css how do i fix a single nested div when scrolling the other layered/nested contents in a container?css 如何在滚动容器中的其他分层/嵌套内容时修复单个嵌套 div?
【发布时间】:2011-08-05 23:28:22
【问题描述】:

我看过一些关于固定位置元素主题的有趣帖子,但是我有一个我无法解决的问题。

我在一个滚动的 div 容器内有许多嵌套的 div,如我的示例 here

<div id="bottom" class="bottombox">
<div id="first" class="firstbox">
<div id="second" class="secondbox">
<div id="third" class="thirdbox">
<div id="top" class="topbox">
</div>
</div>
</div>
</div>


.bottombox
{
margin-top:0px;
margin-left:0px;
Position: absolute;
width: 200px;
height:200px;
overflow:auto;
background-color: darkblue;
}

.firstbox
{
margin-top:10px;
margin-left:10px;
width: 700px;
height:50px;
background-color: lightblue;
}

.secondbox
{
margin-top:20px;
margin-left:10px;
Position: absolute;
width: 700px;
height:50px;
background-color: brown;

}


.thirdbox
{
margin-top:30px;
margin-left:10px;
width: 100px;
height:100px;
/*Position: fixed;*/    
background-color: white;
}


.topbox
{
margin-top:40px;
margin-left:10px;
width: 700px;
height:500px;
background-color: darkgray;
}

如您所见,有许多“层”一起滚动。我遇到的问题是我只希望白框相对于实际上是容器的底框保持固定。

这可以用 CSS 完成吗?如果没有,Jquery 动态更新它的位置呢?

【问题讨论】:

  • 对于初学者,您缺少一个结束 DIV。此外,“Position”属性必须为小写。
  • div需要嵌套吗?我想知道您是否可以通过其他方式实现您想要实现的目标。
  • @diodeus 感谢您指出这一点,抱歉我只是在下班前把它搞砸了!
  • @sassyboy 是的,层是绝对必要的——它们包含图像,而交互作用需要层机制。

标签: jquery css html css-position


【解决方案1】:

我想不出任何办法在 CSS 中做到这一点,但这里有一个 jquery 解决方案:

http://jsfiddle.net/drHam/7/

$("#bottom").scroll(function(){
    var $this = $(this);
    $(".thirdbox").css("top",$this.scrollTop())
                  .css("left",$this.scrollLeft());            

    $(".topbox").css("top", $this.scrollTop()*-1)
                .css("left",$this.scrollLeft()*-1);
});

【讨论】:

    【解决方案2】:

    我认为这对于纯 CSS 是不可能的。

    我用 jquery 制定了一个解决方案,请参阅updated fiddle

    var bottom = $("#bottom");
    var third = $("#third");
    var top = $("#top");
    
    bottom.scroll(function() {
        third.css("left", bottom.scrollLeft());
        third.css("top", bottom.scrollTop());
        top.css("left", -bottom.scrollLeft());
        top.css("top", -bottom.scrollTop());
    });
    

    【讨论】:

    • 您的解决方案也有效,但其他人先到了那里。加一表示平等
    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2014-08-16
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多