2010-06-16 75 views
2

以下javascript代碼在Opera(v10.5x)中完美運行,但在Firefox(v3.6)和IE8中失敗。Javascript樣式分配僅適用於Opera(但不適用於Firefox或IE8)

 

function HighlightBox(elementid,highlight) 
{ 
     var hstyle="none"; 

     if (highlight) 
     {   
     switch (elementid) 
     { 
       case 'emailbox': 
       case 'lastnamebox': 
       case 'firstnamebox': 
       case 'campusbox':       
       hstyle="width:275px;height:70px;border:2px solid red;";               
       break; 
       case 'isdbox': 
       hstyle="width:275px;height:100px;border:2px solid red;"; 
       break; 
     } 
     } 

    document.getElementById(elementid).style = hstyle; 
} 
 

我已經嘗試了個人作業,如:

 

document.getElementById(elementid).style.width="275px"; 
... 
 

但這些似乎並沒有擦出火花。

我很感謝在這件事上的任何幫助。 謝謝 艾附註

+0

瀏覽器中是否有錯誤信息? – Billy 2010-06-16 16:21:23

+1

另外,請確保在頁面加載過程中調用該函數。您必須在window.onload事件中調用該函數。否則,你會得到「document.getElementById(elementid)」爲空錯誤 – Billy 2010-06-16 16:27:39

回答

3

爲了這個目的,你可以嘗試使用cssText屬性,是widely supported

document.getElementById(elementid).style.cssText = "width:275px;height:100px;border:2px solid red;" 

檢查上面的例子here

+0

那麼CMS,你的建議使用.cssText在所有瀏覽器中運行良好。我使用Aptana(v2.0.4)IDE作爲我的javascript和HTML編輯器,並且我嘗試了幾種Aptana'autocompletion'下拉列表中的'.style'組合。 ,在閱讀你的建議後,我回到Aptana看到我錯過了這個組合,Aptana沒有在下拉列表中列出'cssText'。我對此非常驚訝。無論如何,再次感謝您的建議,它工作得很好。 Ai Pragma – 2010-06-17 03:22:35

+0

@AiPragma:'cssText'屬性是[DOM Level 2風格標準](http://www.w3.org/TR/DOM-Level-2-Style/css.html)的一部分(是CSSRule'接口的成員),奇怪的是,Aptana沒有列出這個屬性......無論如何歡迎來到SO,我很樂意幫助,記住你可以標記你的問題的最佳答案[接受] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),看看[FAQ](http://stackoverflow.com/faq):-) – CMS 2010-06-17 04:41:54

相關問題