单击 link 后 Div 动画带有 Javascript - 怎么样?

Div animation with Javascript after clicking on a link - how?

我想在单击 link 后为 div 设置动画。当您单击 "About" 时,应该更改其高度。 CSS 文件中的高度设置为“0em”。如果我写 "document.getElementById('about-div').style.height = '';" 它会起作用,但它会突然跳动,而不是动画。现在我尝试了这段代码,但不幸的是,它不起作用:

CSS:

.about-div {position:absolute;top:100vh;left:0em;width:100vw;height:0em;z-index:10000;background:white;overflow:hidden;}

.open {
  -webkit-animation: open 1s ease-in 1 forwards;
  animation: open 1s ease-in 1 forwards;
}

.is-paused {
  -webkit-animation-play-state: paused;
  animation-play-state: paused;
}

@keyframes open {
  0%   {height:0em;}
  1%     {height:'';}
  100% {height:'';}
}

@-webkit-keyframes open {
  0%   {height:0em;}
  1%     {height:'';}
  100% {height:'';}
}

@keyframes close {
  0%   {height:'';}
  100% {height:0em;}
}

@-webkit-keyframes close {
  0%   {height:'';}
  100% {height:0em;}
}

HTML:

<a href="javascript:openAbout()">About</a>

<div class="about-div open is-paused">
   <p>Some Content</p>
</div>

...和 ​​Javascript 代码:

function openAbout()  {
  <script>
    document.querySelector('.about-div').classList.remove('is-paused');
  </script>
}

有什么想法吗?

函数需要在脚本标签中,而不是函数内部的脚本标签。

<script>
function openAbout()  {
    document.querySelector('.about-div').classList.remove('is-paused');
}
</script>

最初:

'href' 不适用于调用函数。大多数 HTML 元素都有一个 'onclick' 标签用于执行此操作。

<a href="#" onclick="openAbout()">About</a>

并且您需要删除上面提到的 '' 标签,这样您的代码如下所示:

function openAbout() {
    document.querySelector('.about div').classList.remove('is-paused');
}

请参阅my fiddle

您应该从 JS 函数中删除 script 标签。你的 JS 的所有部分都应该在如下的脚本标签中。

<script>
function openAbout() {
    document.querySelector('.about-div').classList.remove('is-paused');
}
</script>

另外,我觉得用动画来动画高度有点麻烦,所以我改用了过渡。请看下面的demo(为了方便观看,我去掉了底部的定位,你用的时候可以放回去)。

function openAbout() {
    document.querySelector('.about-div').classList.remove('is-paused');
}
body { background: #ddd; }
.about-div {
    position:absolute;
    left:0em;
    width:100vw;
    z-index:10000;
    background:white;
    overflow:hidden;
    transition: max-height 5s;
}
.open {
    max-height: 999px;
}
.is-paused {
    max-height: 0px;
}
<a href="#" onclick="openAbout()">About</a>

<div class="about-div open is-paused">
    <p>Some Content</p>
</div>