2013-11-20 127 views
5

我有以下HTML:位置絕對格:滾動DIV

<div class="container"> 
<div class="scrollable-block"> 
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 
    <div class="absolute-div"></div> 
</div> 

和CSS:

.container { 
    width: 200px; 
    height: 300px; 
    background: green; 
} 

.scrollable-block { 
    width: 200px; 
    max-height: 250px; 
    overflow: scroll; 
    position: relative; 
} 

.absolute-div { 
    width: 20px; 
    height: 20px; 
    background: purple; 
    position: absolute; 
    top: 0; 
    right: -10px; 
} 

這裏是一個現場演示:http://jsfiddle.net/BYTam/1/

綠色的div是容器,並有一個固定的寬度。黃色div在它內部,並具有最大高度和溢出y:滾動。它的意思是與綠色的寬度相同。我試圖將紫色div相對於黃色div絕對定位,但是在綠色div之外 - 原因是我不希望黃色div具有水平滾動條。這甚至有可能嗎?

謝謝!

+0

也許你可以把位置:相對.container而不是.scrollable塊?你覺得可以嗎? –

+0

不,它需要與.scrollable-block相關。這是一個更復雜的結構的例子,需要以這種方式行事。 –

回答

0

如果你不想水平滾動條只是改變overflow:scroll

overflow-y:scroll; 
overflow-x:hidden; 
+0

是的,但這種方式絕對(紫色)div保持隱藏。 –

+0

奇怪的是,對我來說,紫色塊在可滾動塊的右上角是可見的 –

1

你不能用你當前的標記做到這一點。絕對div將始終觸發水平滾動條,因爲它嵌套在可滾動塊內。似乎現代瀏覽器不允許overflow-x:with overflow-y:scroll。

+0

是否有一種方法可以讓絕對div出現在容器div之外? Z-索引似乎不起作用。 –

+0

@YavorPunchev - 不是不改變HTML(或使用JavaScript改變HTML/DOM) –

0

我不認爲有可能讓絕對div跳出滾動塊。我跑過了同樣的問題,這是我如何修復它:

<div class="absolute-div"></div> // replace it, put it in the main container. 

$(".absolute-div").css({"top":play with this+"px"}); 
// on scroll of the "scrollable-block" change the ".absolute-div" "top" property using Jquery.