2012-01-20 88 views
1

我有以下遺留代碼,使用從AJAX調用返回的結果在表單輸入下創建彈出式「自動完成」框。此代碼在Firefox 6和IE9正常工作 - 它會彈出一個小格(造型就是Chrome會顯示在開發者工具):Chrome無法正確顯示Javascript createElement div?

<div id="theDiv" style="position: absolute; left: 0px; top: 21px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: green; border-right-color: green; border-bottom-color: green; border-left-color: green; border-top-width: 2px; border-right-width: 2px; border-bottom-width: 2px; border-left-width: 2px; border-image: initial; background-color: white; z-index: 1; visibility: hidden; "><div style="visibility: visible; ">[...autocomplete text here...]</div></div> 

我可以在FF和IE瀏覽器看到這個<div>,但瀏覽器就會顯示一個<div>那似乎已經倒塌到了邊界。奇怪的是,如果我在this.oDiv.style.visibility = "visible";行的javascript代碼中使用開發人員工具設置了斷點,則Chrome會創建<div>並將其顯示爲向下摺疊到邊框的大小,但如果切換到開發人員工具中的元素選項卡以試着看看爲什麼,Chrome似乎重新計算了一些東西,我的<div>突然出現並正確顯示。如果我刷新,事情再次被打破。

這是一個Chrome的bug,還是我的代碼有問題?

相關的代碼:

AutoComplete.prototype.onchange = function() 
{ 
    // clear the popup-div. 
    while (this.oDiv.hasChildNodes()) 
     this.oDiv.removeChild(this.oDiv.firstChild); 

    // get all the matching strings from the AutoCompleteDB 
    var aStr = new Array(); 
    this.db.getStrings("", "", aStr); 

    // add each string to the popup-div 
    var i, n = aStr.length; 
    for (i = 0; i < n; i++) 
    { 
     var iDiv = document.createElement('div'); 

     var myText = document.createTextNode(aStr[i]);   
     iDiv.appendChild(myText);  

     iDiv.FormName = this.FormName; 

     iDiv.onmousedown = AutoComplete.prototype.onDivMouseDown; 
     iDiv.onmouseover = AutoComplete.prototype.onDivMouseOver; 
     iDiv.onmouseout = AutoComplete.prototype.onDivMouseOut; 
     iDiv.AutoComplete = this; 
     iDiv.style.visibility = "visible"; 
     this.oDiv.appendChild(iDiv); 

    } 
    this.oDiv.style.visibility = "visible"; 
} 

回答

0

貌似「theDiv」絕對定位,所以要絕對確保:)你需要指定不僅是它的頂部和左側而且右側和底部(或寬度和)請參閱this瞭解更多有關您的案例中的元素渲染的細節。

+0

根據你給我的w3.org鏈接,我應該能夠指定自動寬度/右,瀏覽器將解決寬度? 「3.'寬度'和'右'是'自動','左'不是'自動',那麼寬度會縮小到適合的範圍,然後解決'正確'」Chrome忽略寬度:自動;右:自動;造型,或至少沒有區別。我仍然在Chrome和Firefox/IE中獲得一個1像素的塊,其大小根據其包含的文本而定。 –

0

我不確定這是否是您需要的。但我有類似的問題。我在按鈕點擊事件時在我的頁面上動態添加輸入框。 當並沒有獲得對按鈕單擊事件在Chrome中添加的輸入框中我的腳本標記如下:

<script type="text/x-javascript" language="javascript"> 

注意,類型爲文本/ X-的JavaScript。 然後我將它改爲text/javascript然後它就起作用了。 我剛剛解決了這個問題,所以不知道這兩種類型的區別。

+0

感謝您的迴應,但這不是同一個問題。在我的情況下,元素被添加,但大小不正確(儘管通過Chrome的開發工具可以看到內容,但實際上顯示爲1像素塊)。 –