JavaScript 切换在第一次按下时不起作用



问题在标题中
我已经尝试修复这个问题2个小时了,主要是在谷歌上搜索修复程序,但我似乎找不到任何工作。所以现在我来了。

无论如何,我做的javascript切换有问题。

我要做的:
创建一个展开/折叠按钮,该按钮仅在单击箭头时展开/折叠方框

这是HTML;

<a id="expand1" value="OFF" type="button" class="btn btn-link collapsed" onclick="toggle(this)">
<div class="right">
<i id="arrow" class="animate-icon fa fa-solid fa-angle-up"></i> 
</div>
</a>
<div id="answer1">
answer
</div>

这是JS;

function toggle(button) {
if (button.value == "OFF") {
button.value = "ON";
document.getElementById('answer1').style.opacity = "1";
document.getElementById('answer1').style.height = "350px";
}
else {
button.value = "OFF";
document.getElementById('answer1').style.opacity = "0";
document.getElementById('answer1').style.height = "0px";
}
}

到目前为止我所尝试的;

  • 在谷歌上搜索答案
  • stackoverflow搜索答案
  • 定义">打开";或">关闭";作为变量,并将其用作切换
  • 尝试{if([variable].style.height=="350px"({}}(我不知道这是否有效,只是想试试。(

如果有人知道如何解决这个问题,如果你能告诉我我能做些什么来解决这个问题的话,我将不胜感激。谢谢

没有属性值,这就是为什么第一次点击锚点-条件转到其他分支时,我建议使用答案的不透明性作为行动的决定因素:

function toggle(button) {
var ans = document.getElementById('answer1');
if (ans.style.opacity != '1') {
ans.style.opacity = "1";
ans.style.height = "350px";
}
else {
ans.style.opacity = "0";
ans.style.height = "0px";
}
}
<a id="expand1" value="OFF" type="button" class="btn btn-link collapsed" onclick="toggle(this)">
toggle
</a>
<div id="answer1" style="opacity:0;">
answer
</div>

最新更新