HTML / JS-切换显示/隐藏动画

时间:2018-08-03 23:17:45

标签: javascript html

我的问题是我需要创建一个切换显示/隐藏窗口,但是我需要将其设置为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

2 个答案:

答案 0 :(得分:1)

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

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

您可以使用三元运算符简化此功能:

function myFunction() {
    var x = document.getElementById("myDIV");
    (x.style.bottom === "0px")? x.style.bottom = "300px": 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>

要为transition CSS属性添加bottom,只需将transition: bottom 1s添加到div中,以便当bottom属性更改时,它将开始持续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>

答案 1 :(得分:0)

要进一步获得hev的答案,您可以使用Javascript三元运算符将其清除一些(无法在此处添加注释):

g++ main.cpp -fopenmp