2017-07-07 14 views
0

要素の表示が何もない値から別の値に変化すると、そのアニメーション(存在する場合)がアクティブになります。 誰もこれを防ぐ方法を知っていますか?要素を表示すると、CSSでアニメーションがアクティブにされます。

また、なぜこのようなことが起こるのかを理解することは良いことです。 DOMがリフローされているからですか?ここで

は、私は参考のために何を意味するかの例です:

https://jsfiddle.net/darlyp/2p2q767r/

HTML

<div class="red-square"></div> 
<br/> 
<button id="btn"> 
    Hide and Show square 
</button> 

CSS

.red-square{ 
    width: 100px; 
    height: 100px; 
    background-color: red; 
    display: inline-block; 
    animation: 1s both moveSquare 1; 
} 
@keyframes moveSquare{ 
    0%{ 
    margin-left: 0px; 
    } 
    50%{ 
    margin-left: 400px; 
    } 
    100%{ 
    margin-left: 0px; 
    } 
} 

JS

あなたはそれを表示する場合

https://jsfiddle.net/darlyp/2p2q767r/

+0

あなたは 'display'は「インライン・ブロック」に設定されている' moveSquare'アニメーションを発射したくない意味ですか? – showdev

+2

代わりに 'opacity/height'を切り替えることはできますか? https://jsfiddle.net/2p2q767r/1/ –

+0

@showdevはいいいえ – Darly

答えて

2

210は、あなたがanimation-play-statepausedにを設定することができます。

JSfiddle

document.getElementById('btn').addEventListener("click", function() { 
 
    var currentDisplay = document.querySelector('.red-square').style.display; 
 
    if (currentDisplay === 'none') { 
 
    document.querySelector('.red-square').style.display = 'inline-block'; 
 
    document.querySelector('.red-square').style.animationPlayState = 'paused'; 
 
    } else { 
 
    document.querySelector('.red-square').style.display = 'none'; 
 
    } 
 
})
.red-square{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    display: inline-block; 
 
    animation: 1s both moveSquare 1; 
 
} 
 
@keyframes moveSquare{ 
 
    0%{ 
 
    margin-left: 0px; 
 
    } 
 
    50%{ 
 
    margin-left: 400px; 
 
    } 
 
    100%{ 
 
    margin-left: 0px; 
 
    } 
 
}
<div class="red-square"></div> 
 
<br/> 
 
<button id="btn"> 
 
    Hide and Show square 
 
</button>

1

もう一つの方法は、ページ上の任意のスペースを占有しないように、代わりにopacityを切り替え、それが隠されていたときに0heightを変更することです。

document.getElementById('btn').addEventListener("click", function() { 
 
    document.querySelector('.red-square').classList.toggle('hide'); 
 
})
.red-square { 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    display: inline-block; 
 
    animation: 1s both moveSquare 1; 
 
} 
 

 
@keyframes moveSquare { 
 
    0% { 
 
    margin-left: 0px; 
 
    } 
 
    50% { 
 
    margin-left: 400px; 
 
    } 
 
    100% { 
 
    margin-left: 0px; 
 
    } 
 
} 
 

 
.hide { 
 
    opacity: 0; 
 
    height: 0; 
 
}
<div class="red-square"></div> 
 
<br/> 
 
<button id="btn"> 
 
    Hide and Show square 
 
</button>

関連する問題