如何让div展开

伙计们,


当单击 div 打开时,以下代码工作正常,但我需要在再次单击按钮时将其关闭


这是JS


<script type="text/javascript">

function slide(){

document.getElementById("sliding").style.maxHeight = "1000px";

}

</script>

这是CSS


#sliding{

    transition: 0.5s;

    max-height: 0px;

    overflow: hidden;

}

和html


 <button onclick ="slide();" class="btn btn-primary">ADD COMMENT</button> 




  <div id = "sliding">

    <p>TEST</p>

    </div>

有人可以帮我让它在再次单击按钮时隐藏 div 吗?


提前非常感谢


喵喵时光机
浏览 112回答 3
3回答

撒科打诨

将状态添加到动态更改的 html 中。有多种方法。以下代码使用可见性已切换的 div 上的 css 属性 maxHeight 的值,该属性在将文本变为可见时无论如何都会更改。这不是最干净的方法,但会显示原理并尽量减少对给定代码的更改:function slide(){&nbsp; &nbsp; if (parseInt(document.getElementById("sliding").style.maxHeight) === 0) {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("sliding").style.maxHeight = "1000px";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("sliding").style.maxHeight = "0px";&nbsp; &nbsp; }}&nbsp; &nbsp; #sliding{&nbsp; &nbsp; &nbsp; transition: 0.5s;&nbsp; &nbsp; &nbsp; max-height: 0px;&nbsp; &nbsp; &nbsp; overflow: hidden;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;<button onclick ="slide();" class="btn btn-primary">ADD COMMENT</button>&nbsp;&nbsp; &nbsp; &nbsp;<div id = "sliding">&nbsp; &nbsp; &nbsp; &nbsp; <p>TEST</p>&nbsp; &nbsp; &nbsp;</div>

明月笑刀无情

您可以在函数中包含一个检查,以查看当前的 maxHeight 是什么,并根据结果更改 maxHeight 的状态。如果您决定稍后更改 maxHeight,请使用不等式运算符,如下所示。function slide(){&nbsp; elem = document.getElementById("sliding");&nbsp; elemHeight = elem.style.maxHeight;&nbsp; elemHeight.replace("px", "");&nbsp; if (elemHeight > "0") {&nbsp; &nbsp; elem.style.maxHeight = "0px";&nbsp; }&nbsp; else {&nbsp; &nbsp; elem.style.maxHeight = "1000px";&nbsp; }}

慕桂英4014372

您可以使用 classList.toggle 方法。function slide(){&nbsp; document.getElementById("sliding").classList.toggle('sliding-show')}#sliding{&nbsp; &nbsp; transition: 0.5s;&nbsp; &nbsp; max-height: 0px;&nbsp; &nbsp; display: none;}#sliding.sliding-show {&nbsp; display: block;&nbsp; max-height: 1000px;}<button onclick ="slide()" class="btn btn-primary">ADD COMMENT</button>&nbsp;&nbsp; <div id="sliding">&nbsp; &nbsp; <p>TEST</p>&nbsp; &nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5