【问题标题】:Accessing @keyframes through JS通过 JS 访问@keyframes
【发布时间】:2016-08-12 22:07:01
【问题描述】:

我有一个 html/css/js 模态在 fadeIn 和 slideIn 前提下工作,但我似乎无法让它在关闭时做相反的事情......它只是很难跳到“不存在”。

我在 JS 中的关闭功能只是采用 modal.style.display="none" 但是有没有办法访问我在我的 css 中添加的@keyframes 以进行平滑的反转?

HTML:

<h2>Bottom Modal</h2>

<button id="button">Click Me</button>

<div id="modal">

<div id="modal-content">
    <div id="modal-header">
        <span id="close">&times</span>
        <h2>modal header</h2>
    </div>

    <div id="modal-body">
        <p>Some text in the modal body</p>
        <p>Some other text in the modal body</p>
    </div>

    <div id="modal-footer">
        <h2>modal footer</h2>
    </div>

</div><!--modal-content-->
</div><!--modal div-->

CSS:

#modal
{
position: fixed;
z-index:1;
left:0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color:rgba(0,0,0,0.4);
-webkit-animation-name: fadeIn;
-webkit-animation-duration: 0.4s;
animation-name: fadeIn;
animation-duration: 0.4s;
display: none;
}

#modal-content
{
position: fixed;
bottom: 0;
backgroun-color: #fefefe;
width: 100%;
-webkit-animation-name: slideIn;
-webkit-animation-duration: 0.4s;
animation-name: slideIn;
animation-duration: 0.4s;

}

#close
{
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}

#close:hover, #close:focus
{
color: #000;
text-decoration: none;
cursor: pointer;
}

#modal-header
{
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}

#modal-footer
{
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}

#modal-body
{
padding: 2px 16px;
background-color: white;
}

 @-webkit-keyframes slideIn
 {
 from {bottom: -300px; opacity: 0}
 to {bottom: 0; opacity: 1}
 }

@keyframes slideIn
 {
 from {bottom: -300px; opacity: 0}
 to {bottom: 0; opacity: 1}
 }

@-webkit-keyframes fadeIn
{
from {opacity: 0}
to {opacity: 1}
}

@keyframes fadeIn
{
from {opacity: 0}
to {opacity: 1}
}

JS:

var modal = document.getElementById("modal");

var button = document.getElementById("button");

var close = document.getElementById("close");

button.onclick = function()
{
modal.style.display="block";
};

close.onclick = function()
{
modal.style.display="none";
};

window.onclick = function(event)
{
if(event.target == modal)
{
modal.style.display="none";
}
};

【问题讨论】:

  • 设置element.style.display='none'后无法为任何东西设置动画。
  • 如果您不介意使用它,我认为您可以使用 jQuery 轻松实现它。除此之外所有的动画都是Opacity: 0 to 1

标签: javascript css css-animations


【解决方案1】:

基于发布的问题:

  • 无法访问 @keyframes 规则 - 没有 巨大的 hacks(将 css 作为文本并使用正则表达式解析规则,即使在 100% 的情况下您也无法做到)

  • 访问关键帧规则对您的要求没有帮助

  • 设置display:none后任何动画都不可能出现

  • 但是,您可以通过 jQuery.keyframes 等 JavaScript 库动态生成、激活、停止和再次播放 @keyframe 动画。

【讨论】:

  • 非常感谢您的详细评论!
猜你喜欢
  • 2021-12-31
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2019-12-28
  • 2020-04-13
相关资源
最近更新 更多