我试图构建一个页面,我可以发布一系列长文本(在这个特殊情况下,歌词)。我已经按照网站上的代码执行类似的操作,但似乎无法使其正常工作。有什么建议?我的代码发布在下面。
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;
}
答案 0 :(得分:3)
getComputedStyle
代替style
。
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;
答案 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");
}
}