2012-12-10 21 views
3

我如何解決DIV另一格在滾動條

<div id="div1"> 
    any not fixed text 
    but this div has scrollbar 

    <div id="div2"> 
    this div is fixed (without scrollbar) 
    </div> 

</div> 

我需要div2固定div1,但不固定到主瀏覽器滾動條。像「將div2粘貼到div1」。

div1有滾動條,這就是爲什麼我需要修復div2

如果我有這樣的:

#div1 { 
    position: absolute; 
} 
#div1 #div2 { 
    position: fixed; 
} 

就會好div1和瀏覽器的窗口這兩個,但我只需要div1

實施例進行測試:

<html> 
<head> 
<style type="text/css"> 
#div1 { 
    border: 1px solid gray; 
    position: absolute; 
    height: 200px; 
    width: 400px; 
    overflow-y: scroll; 
} 
#div1 #div2 { 
    position: fixed; 
    margin-left: 300px; 
} 
</style> 
</head> 
<body> 
    <br><br><br> 
    <div id="div1"> 
     <div id="div2">fixed text</div> 

      <div style="height: 400px;"></div> 
    </div> 

    <div style="height: 1400px;"></div> 
</body> 
</html> 

Q1:如何修正div2div

Q2:在這種情況下如何float: rightdiv2到的div1右側(上例中爲〜margin-left: 350px;

謝謝。

+0

附註:如果你有內部div的ID,那麼你應該在你的css中使用'#div2 {/ * style * /}'而不是'#div1#div2 {/ * style * /}'。 – Roimer

回答

1

的問題是,你不能修復DIV2至DIV1,由於固定一個div是指「以保持div的頂部,從其最近定位的容器內頂測量,常數」。並且通過inner top我的意思是容器的上半部分,隨着用戶的滾動而上下移動。

解決方案(jsfiddle here)將修復div1和div2到外部容器。這將是你的CSS:

<style type="text/css"> 
#container{ 
    border: 1px solid gray; 
    position: absolute; 
    height: 200px; 
    width: 400px; 
} 

#div1{ 
    position: absolute; 
    top: 0; 
    left: 0; 
    right: 0; 
    bottom: 0; 
    overflow-y: scroll; 
} 
#div2 { 
    position: absolute; 
    right: 14px; 
    top: 0px; 
}​ 
</style> 

這你的HTML

<br><br><br> 
<div id="container"> 
    <div id="div1"> 
     <div style="height: 800px;"></div> 
    </div> 
    <div id="div2">fixed text</div>    
</div> 
<div style="height: 1400px;"></div>​​​​​​​​​​​ 
1

固定總是在瀏覽器窗口。您不能在具有滾動條的元素的上下文中使用它。

這將在一定層面開展工作: http://jsfiddle.net/WP7GB/1/

<div id="div1"> 
    <div id="div2">fixed text</div> 
    <div style="height: 400px;"></div> 
</div> 
<div style="height: 1400px;"></div> 

CSS:

#div1 { 
    border: 1px solid gray; 
    position: relative; 
    height: 200px; 
    width: 400px; 
    overflow-y: scroll; 
} 

#div2 { 
    position: absolute; 
    top:0; 
    right:5px; 
} 

JS:

$(document).ready(function(){ 

    var $div2 = $("#div2"); 

    $("#div1").scroll(function(e){ 

     $div2.css("top", this.scrollTop); 

    });   

}); 
+0

它的工作原理,但在我的Chrome瀏覽器中,它有滯後現象 – sirjay