2013-03-02 29 views
0

我正在研究一個小文本框,它將主動顯示不同的文本而不重新加載頁面。我使用JavaScript來插入基於用戶點擊鏈接的文本段落。它的工作原理,但是,我想也插入樣式屬性到動態插入的內容。我想這樣做,因爲div的背景會變黑。使用javascript動態插入文字的樣式

這裏是我的JS

function navClicked(x){ 

     //alert("function activated"); 
     //alert(x); 
     if (x == "aboutButton"){ 
      //alert("About Button"); 
      document.getElementById('information').innerHTML = "About Click"; 
     } 
     else if(x == "faqButton"){ 
      //alert("FAQ Button"); 
      document.getElementById('information').innerHTML = "FAQ Click"; 
     } 
     else if(x == "servicesButton"){ 
      //alert("Services Button"); 
      document.getElementById('information').innerHTML = "Services Click"; 
     } 
     else{ 
      //alert("Contact Button"); 
      document.getElementById('information').innerHTML = "Contact Click"; 
     } 
    } 

下面是與它

<body> 
     <div id="navigation"> 
      <table cellpadding="5"> 
       <tr> 
        <td> 
         <a onClick="navClicked('aboutButton');" style="cursor: pointer; cursor: hand;">ABOUT ATS</a> 
        </td> 
       </tr> 
       <tr> 
        <td> 
         <a onClick="navClicked('faqButton');" style="cursor: pointer; cursor: hand;">FAQ</a> 
        </td> 
       </tr> 
       <tr> 
        <td> 
         <a onClick="navClicked('servicesButton');" style="cursor: pointer; cursor: hand;">SERVICES</a> 
        </td> 
       </tr> 
       <tr> 
        <td> 
         <a onClick="navClicked('contactButton');" style="cursor: pointer; cursor: hand;">CONTACT</a> 
        </td> 
       </tr>    
      </table> 
     </div> 
     <div id="information"> 
      <p> 
       content 
      </p> 
     </div> 
    </body> 

終於CSS

<style> 
body, div, h1, h2, h3, h4, h5, h6, p, ul, img {margin:0px; padding:0px; } 
    p 
    { 
    color:white; 
    } 

    #navigation 
    { 
     height:145px; 
     float:left; 
     width:155px; 
     background:grey; 
    } 
    #navigation table 
    { 
     margin-left:auto; 
     margin-right:auto; 
     color:white; 
    } 

    #information 
    { 
     height:145px; 
     float:left; 
     width:290px; 
     background:black; 
    } 
</style> 

最終產品的工作原理而來的HTML。但是,無論何時將新文本插入框中,它都會變黑。然後你無法閱讀文本。

這裏是一個的jsfiddle http://jsfiddle.net/9xahg/

雖然在撥弄不工作和IM不知道爲什麼。但無論如何,它在所有瀏覽器中按預期工作,但不能讀取新文本。

我該如何解決這個問題?

回答

1

只需添加「顏色:白色」;在#information CSS語句:

#information 
{ 
    height:145px; 
    float:left; 
    width:290px; 
    background:black; 
    color: white; 
} 

而且它的工作;)

+0

哈哈應該想到這是一件顯而易見的那樣。非常感謝你=) – onTheInternet 2013-03-02 22:34:27

+0

不客氣;) – Guicara 2013-03-02 22:35:43

0

JQuery完全是爲了這個,所以你可以引用HTML元素,就像你在CSS中一樣。如果你想使用JavaScript設計元素,我強烈建議你使用jQuery。它將長期節省下來的回報。一旦你有它,有一個特定的.css()函數來幫助你。

1

嘗試添加

color: white; 

到#information代替

這是因爲我的風格與p元素,你不要當你寫新的文本打印出AP元素...

無論是或者你也可以在寫文字時加入ap元素:

document.getElementById('information').innerHTML = "<p>About Click</p>";