2011-08-05 25 views
2

我已經看到了一些關於固定位置元素的有趣帖子,但我有一個問題,我無法解決。css如何在滾動容器中的其他分層/嵌套內容時修復單個嵌套div?

我有一些滾動的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如何動態更新其位置?

+1

對於初學者來說,你缺少一個右DIV。另外,「位置」屬性需要小寫。 –

+0

div是否需要嵌套?我想知道你是否想通過其他方式實現你的目標。 – shashi

+0

@diodeus感謝您指出這一點,道歉我只是在離開工作之前將它們擊垮! – T9b

回答

2

我想不出任何辦法在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); 
}); 
1

我覺得這是不可能的純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()); 
}); 
+0

你的解決方案也適用,但其他人先到那裏。加上一個平等 – T9b