2010年12月9日 星期四

卡到陰的TR與CSS:Display屬性

下面這張圖就是最近在忙著製作的前端介面,分為上下兩半,全部使用jQuery來做。


簡單說明運作方式一下:
上方的欄位可以依照下拉選單來產生表單,
當選取各列之後,可以按加入按鈕加到下方空欄,上方的資料列會消失,
若按下下方各個欄位的取消按鈕,就會清空欄位的值,並且讓上方表單消失的那列回覆顯示。
最多選八個值,確定送出就送到後端比對資料與存檔。

奇怪的事情往往就在最不可能發生的地方發生了,當我辛辛苦的用jQuery把各個事件都處理好,開始測試的時候,卻發現IE下沒有問題,但是FireFox與我最愛的Chrome卻在取消按鈕按下,重建上方表格時出錯了,表格整個亂掉。




經過一番追查....真的被我抓到元兇了。

原先寫在Javascript中要來隱藏與顯示
用的CSS語法是display:none 還有 display:block

在jQuery串接下的寫法類似這個樣子

$(this).parent().parent().css("display","none") //隱藏
$(this).parent().parent().css("display","block") //顯示


這個display:block就是元兇,尤其用在表格元素的隱藏後再回覆...
而且不管我怎麼改變jQuery的寫法也無濟於事

情急之下(其實卡關好幾天),依照Google大神指點的這篇討論串中rf以及Michael Winter的發言:

rf:
It's not a bug in the browser (or browsers) it's a bug in your code.
elements (table rows) have a default display proterty of display:
table-row; That is what makes them table rows.
If you apply display: block; to one then it is no longer a table row, it is
a standard block. It is as if you were to code:
Col1Col2
This cell should take 2 columns
but does not because of the display:block
The reason it "appears" to work with IE is probably because IE is
error-correcting the display property for you.

Michael Winter:
Even that should be unnecessary. Provided that the property is set via the
style attribute (or style object), which it is in this case,
element.style.display = '';
will effectively remove the inline style value allowing the browser to
return to the inherited value.

終於找到問題的答案,又被IE擺了一道。
很開心不用寫個判斷式來判斷連線上來使用者的瀏覽器種類..
有遇到display:block不能在各個瀏覽器正常運作的,可以參考一下。

把代碼改動一下

$(this).parent().parent().css("display","none") //隱藏
$(this).parent().parent().css("display","") //顯示


測試完畢,收工!

1 意見:

匿名 提到...

This is the problem with 'display:block'

Please refer the below link http://thedesignspace.net/MT2archives/000376.html#.UUrg3FfCd1u

If you are hiding tr, then use 'display:table-row' instead of 'display:block' to display that tr,

If you are hiding td, then use 'display:table-cell' instead of 'display:block' to display that td

Use "table-row", no "block" when styling a TR. Perfect!

張貼留言

留言........