首页 > 解决方案 > CSS 或 JS 中的随机

问题描述

需要帮助,想要旋转图像,3 秒后它必须以随机度数停止(从36010800)。当我从最后一个位置单击它时,它开始旋转。

当图像停止时,它会出现一个带有我大量随机引用的区域。它必须是“旋转瓶子”之类的东西

请帮忙,我有一些代码,但不知道如何完成它。

.wheel {
  animation: wheel 3s .5s;
  animation-fill-mode: both;
}

@keyframes wheel {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(10800deg);
  }
}
<head>
  <link rel="stylesheet" href="bottle.css">
  <script src="bottle.js"></script>
</head>
<img id="wheel" class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">

标签: javascripthtmlcss

解决方案


您可以使用 css 自定义属性来执行此操作。首先要做的是为您的转换创建一个属性:

:root{
  --rot: rotate(108000deg);
}

然后用它代替你的硬编码值

@keyframes wheel {
  from { transform: rotate(0);}             
  to { transform: var(--rot); }
}

在这个阶段,一切都应该像以前一样继续工作。

现在您可以使用 javascipt 操作该属性:

var min = 360;
var max = 108000;
var rnd = Math.random()* (max - min) + min;
console.log(rnd);

var wheel = document.querySelector(".wheel");
wheel.style.setProperty("--rot","rotate(" + rnd + "deg)");
:root{
  --rot: rotate(108000deg);
}

.wheel {				
  animation: wheel 3s .5s;	
  animation-fill-mode: both;	
}

@keyframes wheel {
  from { transform: rotate(0);}				
  to { transform: var(--rot); }
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">

如果你想在点击之类的东西上重复动画,你需要做一些解决方法

var min = 360;
var max = 108000;

var wheel = document.querySelector("#wheel");
wheel.addEventListener("click", function(e) {
  e.preventDefault;
  
  // -> removing the class
  wheel.classList.remove("wheel");
  
  // -> triggering reflow /* The actual magic */
  // without this it wouldn't work. Try uncommenting the line and the transition won't be retriggered.
  // Oops! This won't work in strict mode. Thanks Felis Phasma!
  // element.offsetWidth = element.offsetWidth;
  // Do this instead:
  void wheel.offsetWidth;
  
  var rnd = Math.random()* (max - min) + min;
  console.log(rnd);
  wheel.style.setProperty("--rot","rotate(" + rnd + "deg)");
  // -> and re-adding the class
  wheel.classList.add("wheel");
}, false);
:root{
  --rot: rotate(108000deg);
}

.wheel {				
  animation: wheel 3s .5s;	
  animation-fill-mode: both;	
}

@keyframes wheel {			
  to { transform: var(--rot); }
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">


推荐阅读