gpt4 book ai didi

javascript - 使用 Javascript 切换 CSS 显示设置

转载 作者:行者123 更新时间:2023-11-30 11:30:33 26 4
gpt4 key购买 nike

我正在尝试构建一个页面,我可以在其中发布一系列长文本(在本例中为歌词)。我已经按照网站上的代码做了类似的事情,但似乎无法让它发挥作用。有什么建议么?我的代码贴在下面。

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

最佳答案

  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" -->

关于javascript - 使用 Javascript 切换 CSS 显示设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46384714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com