HTML/JS-如何用动画切换显示/隐藏?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (593)

我的问题是,我需要做一个切换显示/隐藏窗口,但不是display: none/block我需要它bottom: 0px/300px所以我可以将CSS转换应用到它上。

你们能找到任何解决方案,让我以我想要的方式实现切换功能吗?

function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
} 
// So this is what I DO NOT want.
// I need it to use bottom:*value*
// instead of display:block/none

提问于
用户回答回答于

可以使用Javascript三元运算符(无法在这里添加注释)来进一步清除它:

html, body{
 overflow-y: auto;
 height: 500px;
 position: relative;
}

<div id="myDIV" style="position: absolute; bottom: 0px; width: 50%; border: 1px solid black;">
    Div
    </div>
    <button style="float: right;" onClick="myFunction()">
        Toggle Bottom Property of #myDiv
    </button>
    <script>
      function myFunction() {
          var x = document.getElementById("myDIV");
          x.style.bottom === "0px" ? x.style.bottom = "300px" : x.style.bottom = "0px";
          }
    </script>
用户回答回答于

只需将函数中的样式属性用法更改为Element.style.displayElement.style.bottom

function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.bottom === "0px") {
        x.style.bottom = "300px";
    } else {
        x.style.bottom = "0px";
    }
} 

html, body{
 overflow-y: auto;
 height: 500px;
 position: relative;
}
<div id="myDIV" style="position: absolute; bottom: 0px; width: 50%; border: 1px solid black;">
Div
</div>
<button style="position: fixed;" onClick="myFunction()">Toggle Bottom Property of #myDiv</button>
<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.bottom === "0px") {
        x.style.bottom = "300px";
    } else {
        x.style.bottom = "0px";
    }
} 
</script>

若要添加transitionbottom属性,只需添加transition: bottom 1s因此,当底部属性发生变化时,它将开始一个持续1秒的转换。

html, body{
 overflow-y: auto;
 height: 500px;
 position: relative;
}

.animateBottom{
    transition: bottom 1s;
}
<div id="myDIV" style="position: absolute; bottom: 0px; width: 50%; border: 1px solid black;" class="animateBottom">
Div
</div>
<button style="position: fixed;" onClick="myFunction()">Toggle Bottom Property of #myDiv</button>
<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.bottom === "0px") {
        x.style.bottom = "300px";
    } else {
        x.style.bottom = "0px";
    }
} 
</script>

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励