繁体   English   中英

单击链接后使用Java的Div动画-怎么做?

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

单击链接后,我想为div设置动画。 当您点击“关于”时,应当更改其高度。 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');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM