Div动画与Javascript后点击一个链接-如何

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

本文关键字:一个 链接 如何 动画 Javascript Div      更新时间:2023-09-26

我想在点击链接后动画一个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>
}

有什么想法吗?

请看我的小提琴

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

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

另外,我认为使用动画来动画高度有点麻烦,所以我使用过渡代替。请参见下面的演示(我删除了底部定位,以便于查看,您可以在使用时将其放回原处)。

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>

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

<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');
}