使用Javascript切换CSS显示设置

时间:2017-09-23 22:11:16

标签: javascript html

我试图构建一个页面,我可以发布一系列长文本(在这个特殊情况下,歌词)。我已经按照网站上的代码执行类似的操作,但似乎无法使其正常工作。有什么建议?我的代码发布在下面。

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;
}

3 个答案:

答案 0 :(得分:3)

  1. 您的代码周围缺少引号。
  2. 您没有传递有效的ID,而是传递变量名而不是字符串。
  3. 要获取在css中设置的css规则,请使用getComputedStyle代替style
  4. 要更改样式,请不要使用包含当前样式的字符串,而是使用样式属性。
  5. &#13;
    &#13;
    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";
      }
    }
    &#13;
    .lyric {
      display: none;
    }
    &#13;
    <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" -->
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

您正在将x.style.display的值复制到xdisplay,然后将xdisplay设置为其他值。相反,尝试:

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

答案 2 :(得分: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");
        }
    }