2013-02-14 73 views
2

我有一個紅色的div在一個固定的位置:頂部和底部是固定的。溢出Firefox和IE9 +

該div包含一個表格,其中一個單元格包含一個可滾動的div,以便內容不能溢出紅色div。

它看起來像這樣在Chrome:

enter image description here

但在Firefox中,內容的增加和溢出了紅盒子:

enter image description here

這裏是我的HTML:

<div id=a> 
    <div id=b> 
     <table id=c border=1> 
      <tr><th height=20 width=20> 
       <input type=button id=but value="Fill cell"> 
      </th><th>A</th></tr> 
      <tr><th>dataname</th> 
       <td><div id=val class=scrollable>cell content</div></td> 
      </tr> 
     </table> 
    </div> 
</div> 

和CSS:

#a { 
    position:fixed; top:20px; left:20px; bottom:50px;width:200px; 
    background:red; 
} 
#b { height:100%; } 
#c { width:100%; height:100%; } 
.scrollable { 
    width:100%; height:100%; 
    overflow-y:auto; 
} 

下面是爲測試一個小提琴:http://jsfiddle.net/xusqc/

我建議你在提交答案之前測試的FF你的建議。

我該如何解決我的代碼在Firefox和IE9 +上我現在在Chrome上的行爲?

請注意,表中第一行的高度可能會在我的應用程序中動態更改。如果我的數據表有更多的行和單元格,解決方案必須適用。

+0

'overflow:scroll'? – 2013-02-14 15:30:23

+0

@queueoverflow它不起作用,我不希望滾動條在不需要時出現。 – 2013-02-14 15:31:01

+0

在td中使用div不是一個好習慣,爲什麼不把id和class傳遞給div的父td?只是一個建議 – Toping 2013-02-14 16:16:32

回答

0

,因爲我無法找到一個跨瀏覽器的純HTML/CSS的解決方案,我不得不使用一些JavaScript(和jQuery,但它可能會,如果我有綁定jQuery的不是很多的事件處理程序沒有完成它在我的細胞中)。

想法是清空包含.scrollable div的單元格,計算它們的高度,重新填充單元格,然後將高度設置爲固定。

這是我寫的功能:當窗口大小

function resetScrollableHeights(){ 
    $sp = $('.scrollable').closest('td'), heights = [], contents = []; 
    $sp.each(function(){ 
     $(this).css('height', 'auto'); // without this, window shrinking would be badly handled 
     contents.push($('.scrollable', this).detach()); // let's empty all scrollables 
    }); 
    $sp.each(function(){ //now store the heights 
     heights.push($(this).height()); 
    }); 
    $sp.each(function(){ // refill the scrollables and fix the heights 
     $(this).append(contents.shift()).css('height', heights.shift()); 
    }); 
} 

的函數被調用:

$(window).resize(resetScrollableHeights); 

而且它也必須調用時的.scrollable DIV的內容發生變化。

我在Chromium/Ubuntu,Chrome/Android,Firefox/Ubuntu和IE9/Win7上測試過它。由於在基於WebKit的瀏覽器上沒有任何用處,因爲我沒有任何純HTML/CSS的bug,它可以通過一些檢測來停用,但我更喜歡我的代碼免於瀏覽器檢測。

Demonstration

-1
  1. <td>更改爲<td class="scrollwrap">,其中包含您的目標div。
  2. 更新你的CSS:

.scrollwrap { position:relative; } 
.scrollable { 
    position:absolute; width:100%; height:100%; top:0; left:0; right:0; bottom:0; 
    overflow:auto; 
} 

但要注意:

  • height:100%只能當父母也有一個特定的高度,並不總是與計算工作高度;
  • position:absolute元件使用left & righttop & bottom時,某些瀏覽器無法計算寬度&高度
  • overflow-yoverflow-x有一些使用限制。
+0

我的結構的整個點是爲紅色格子計算出一個高度。所以這是行不通的。 – 2013-02-14 15:54:35

+0

表單元格不能定位,甚至不能相對。所以絕對div不會相對於表格單元定位。 – Simon 2013-02-14 15:55:10

+0

@Simon參見http://stackoverflow.com/questions/4564638/using-position-relative-absolute-within-a-td並試用它。 – 2013-02-14 21:08:00