2017-09-23 50 views
0

我試圖建立一個頁面,我可以發佈一系列長文本(在這種特殊情況下,歌詞)。我遵循網站上的代碼做類似的事情,但似乎無法使其工作。有什麼建議麼?我的代碼發佈在下面。使用Javascript來切換CSS顯示設置

HTML

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <link rel="stylesheet" href="css.css"> 
    <script> 
     <!-- 
     function toggle(ID) { 
      var x = document.getElementById(ID); //get lyrics element 
      var xdisplay = x.style.display; // get CSS display settings 

      //Change CSS display setting 
      if (xdisplay == none) { 
       xdisplay = "block" 
      } 
      else { 
       xdisplay = "none" 
      } 
      --> 
    </script> 
</head> 
<body> 
    <button onclick="toggle(l1)" id="lyric1">Click Here for Lyrics</button><br> 
    <button onclick="toggle(l2)" id="lyric2">Click Here for Lyrics</button><br> 
    <button onclick="toggle(l3)" id="lyric3">Click Here for Lyrics</button><br> 

    <p class=lyric id=l1> Lyrics 1 </p> 
    <p class=lyric id=l2> Lyrics 2 </p> 
    <p class=lyric id=l3> Lyrics 3 </p> 

</body> 
</html> 

CSS:

.lyric { 
    display: none; 
} 

回答

2
  1. 你錯過了周圍的所有代碼的報價。
  2. 你沒有通過有效的ID,你傳遞的是變量名而不是字符串。
  3. 要獲得在css中設置的css規則,請使用getComputedStyle而不是style
  4. 要更改樣式,請不要使用保存當前樣式的字符串,而應使用樣式屬性。

function toggle(ID) { 
 
    var x = document.getElementById(ID); //get lyrics element 
 
    var xdisplay = getComputedStyle(x, null).display; // get CSS display settings 
 
    //Change CSS display setting 
 
    //Change x.style.display, not xdisplay 
 
    if (xdisplay == "none") { 
 
    x.style.display = "block"; 
 
    } else { 
 
    x.style.display = "none"; 
 
    } 
 
}
.lyric { 
 
    display: none; 
 
}
<button onclick="toggle('l1')" id="lyric1">Click Here for Lyrics</button><br> <!-- changed l1 to 'l1' --> 
 
<button onclick="toggle('l2')" id="lyric2">Click Here for Lyrics</button><br> <!-- changed l2 to 'l2' --> 
 
<button onclick="toggle('l3')" id="lyric3">Click Here for Lyrics</button><br> <!-- changed l3 to 'l3' --> 
 

 
<p class="lyric" id="l1"> Lyrics 1 </p> <!-- changed l1 to "l1" and lyric to "lyric" --> 
 
<p class="lyric" id="l2"> Lyrics 2 </p> <!-- changed l2 to "l2" and lyric to "lyric" --> 
 
<p class="lyric" id="l3"> Lyrics 3 </p> <!-- changed l3 to "l3" and lyric to "lyric" -->

+0

感謝您的明確答案。在問題上標記,是否有可能在按下另一個按鈕時恢復l1的顯示設置? –

+0

@ M.Winter如果通過恢復你的意思是'display:none',使用一個條件:'if(ID!=='l1'){x.style.display ='none'; }'。 –

0

您的x.style.display的值複製到xdisplay,然後設置xdisplay爲其他值。相反,嘗試:

if (xdisplay == "none") { 
    x.style.display = "block"; 
} else { 
    x.style.display = "none"; 
} 
0

您正在使用錯誤的代碼,因爲你錯過了一些引號和花括號,

首先解決你的語法錯誤,那麼,試試這個JS代碼,它工作正常:

function toggle(ID) { 
     var x = document.getElementById(ID); 
     var xdisplay = x.getAttribute("class"); 

     if (xdisplay) { 
      x.removeAttribute("class"); 
     } 
     else { 
      x.setAttribute("class", "lyric"); 
     } 
    }