这是下面的这个非常简单的代码段。
运行它时,您可以看到专辑说明,如果单击span
,则会出现歌曲歌词,并且说明消失。如果再次单击它,您将看到我的问题:描述和歌词均可见,之后单击跨度不再起作用
但是我想要实现的是使代码像那个bug(或类似的东西)一样工作,如果歌曲歌词可见,则隐藏描述,如果描述可见,则隐藏歌词
我尝试了其他if
,else if
或else
语句的一些变体,还尝试了for
循环中的某些功能,但是我无法使其正常工作
你能告诉我我怎么能做到吗?谢谢你的帮助!
function showlyrics(){
document.getElementById("albuminfo").style.display="none";
var lyrics=document.getElementById("songlyrics");
lyrics.style.display = (lyrics.style.display === 'block' ? 'none' : 'block');
if(lyrics.style.display==="none"){
document.getElementById("albuminfo").style.display="block";
//whatever;
//If I write anything after setting albuminfo a block display (UNCOMMENT "whatever;" TO SEE) and I close it, it's actually working as I want it, but I have no idea why, if you could explain this too, I'd appriciate it
}
//I don't know if this part is necessarry, so I'll just leave it here
var hideotherlyrics = document.getElementsByClassName("lyrics");
var i;
for (i = 0; i < hideotherlyrics.length; i++) {
hideotherlyrics[i].style.display = "none";
document.getElementById("songlyrics").style.display="blocK";
}
}
#starslyrics{
position:absolute;
top:3%;
right:40%;
font-size:25px;
font-weight:bold;
}
.hover:hover,.hover a:hover{
border-radius:5px;
border:none;
cursor:pointer;
background-color:red;
color:white;
}
.lyrics{
display:none;
position:relative;
margin-top:50px;
font-size:18px;
}
#albuminfo{
text-align:justify;
width:400px;
font-size:18px;
margin-top:50px;
}
<div id="lyrics">
<p id="albuminfo">
THIS IS THE <strong>ALBUM DESCRIPTION</strong><br><br> IF THIS IS VISIBLE, THE SONG LYRICS SHOULDN'T BE
</p>
<p class="lyrics" id="songlyrics">
THIS IS THE <strong>SONG LYRICS</strong><br><br> IF THIS IS VISIBLE, THE ALBUM DESCRIPTION SHOULDN'T BE
</p>
<span class="hover" onclick="showlyrics()" id="starslyrics">Click here</span>
</div>
最佳答案
您应该在showlyrics()
函数之外定义和设置初始值。否则,它们将不存储显示状态,并且每次您单击该功能时,它将重置以前的状态。
var description = document.getElementById("albuminfo");
var lyrics = document.getElementById("songlyrics");
description.style.display = "none";
lyrics.style.display = "block";
function showlyrics(){
if(lyrics.style.display === "block"){
description.style.display = "block";
lyrics.style.display = "none";
} else {
description.style.display = "none";
lyrics.style.display = "block";
}
}
#starslyrics{
position:absolute;
top:3%;
right:40%;
font-size:25px;
font-weight:bold;
}
.hover:hover,.hover a:hover{
border-radius:5px;
border:none;
cursor:pointer;
background-color:red;
color:white;
}
.lyrics{
display:none;
position:relative;
margin-top:50px;
font-size:18px;
}
#albuminfo{
text-align:justify;
width:400px;
font-size:18px;
margin-top:50px;
}
<div id="lyrics">
<p id="albuminfo">
THIS IS THE <strong>ALBUM DESCRIPTION</strong><br><br> IF THIS IS VISIBLE, THE SONG LYRICS SHOULDN'T BE
</p>
<p class="lyrics" id="songlyrics">
THIS IS THE <strong>SONG LYRICS</strong><br><br> IF THIS IS VISIBLE, THE ALBUM DESCRIPTION SHOULDN'T BE
</p>
<span class="hover" onclick="showlyrics()" id="starslyrics">Click here</span>
</div>