显示/隐藏带有动画的元素 [英] Show / Hide elements with animation

查看:43
本文介绍了显示/隐藏带有动画的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个网站,并试图创建一个将切换div元素可见性的按钮.它现在对我有效,但我想向其中添加动画,但我无法将其拉开.

I'm creating a website and i'm trying to make a button that will toggle the visibility of a div element. it works for me right now but I want to add an animation to it and I just can't pull it off.

我尝试将"block" 更改为 fadeIn(),将"none" 更改为 fadeOut()但这没用.

I tried changing the "block" to fadeIn() and the "none" to fadeOut() but that didn't work.

有什么想法吗?

function pcsh1() {
  var x = document.getElementById("pc1");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<button onclick="pcsh1()">Show / Hide PC 1</button>
<div id="pc1">
  <textarea rows="2" cols="20" placeholder="PC Name" class="pcbox">PC Name: </textarea>
  <textarea rows="2" cols="20" placeholder="Alignment" class="pcbox">Alignment: </textarea>
  <textarea rows="2" cols="20" placeholder="Max HP" class="pcbox">Max HP: </textarea>
  <textarea rows="2" cols="20" placeholder="Current HP" class="pcbox">Current HP: </textarea>
</div>

目前的输出效果很好,但我希望它具有动画效果.

The output currently is great but I would prefer it to have an animation.

推荐答案

我建议使用动画友好型不透明度道具来切换隐藏/显示,而不是以以下方式显示:

I would suggest toggling hide/show using the animation-friendly opacity prop instead of display in the following manner:

function pcsh1() {
    var x = document.getElementById("pc1");
    if (x.classList.contains("hide")) {
      x.classList.remove("hide");
    } else {
      x.classList.add("hide");
    }
}

并添加CSS过渡:

#pc1 {
  opacity: 1;
  transition: opacity 1s;
}
#pc1.hide {
  opacity: 0;
}

这是一个示例代码笔: https://codepen.io/mikeCky/pen/WWjLEq

here is an example codepen: https://codepen.io/mikeCky/pen/WWjLEq

这篇关于显示/隐藏带有动画的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆