【问题标题】:How to create a rain effect that is triggered by an event?如何创建由事件触发的下雨效果?
【发布时间】:2019-05-05 11:35:28
【问题描述】:

我正在尝试使图像下降,类似于下雨效果,但我只希望它由事件侦听器触发。

目前,我正在附加一个 div 并为下降效果设置动画,但每个额外的事件触发器随后都附加在第一个事件的下方/旁边。

function appendImage() {
  var img = document.createElement('img');
  img.setAttribute('src', 'http://pixelartmaker.com/art/3ba7f5717ac3c63.png');
  $('#action').append(img);
}
@keyframes slidedown {
  0% {
    margin-top: 0%;
  }
  100% {
    margin-top: 150%;
  }
}

img {
  animation-duration: 20s;
  animation-name: slidedown;
  height: 100px;
  width: 100px;
}
<input type="button" value="Test Button" onclick="appendImage();" />
<div id="action"></div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

我试图让图像从 x 轴上的随机位置生成,但始终从屏幕顶部生成。

codepen 在这里。

【问题讨论】:

标签: javascript jquery html css css-animations


【解决方案1】:

您可以在此处使用 fixed position 以便元素可以在视口中独立移动 - 现在您可以为动画使用 top 值和 left 随机水平展开。

还要注意animation-fill-mode: forwards 的用法,它确保动画后图像不会回到窗口顶部。

见下面的演示和updated codepen here:

var rainDiv = document.querySelector('#action');
function appendImage() {
  var img = document.createElement('img');
  img.setAttribute('src', 'http://pixelartmaker.com/art/3ba7f5717ac3c63.png');
  img.style.left = Math.floor(Math.random() * 100) + 'vw';
  rainDiv.appendChild(img);
}
img {
  position: fixed;
  animation-duration: 20s;
  animation-name: slidedown;
  animation-fill-mode: forwards;
  height: 100px;
  width: 100px;
  top: 0;
}

@keyframes slidedown {
  to {
    top: 120%;
  }
}
<input type="button" value="Test Button" onclick="appendImage();" />
<div id="action"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多