javascript - CSS 或 JS 中的随机
问题描述
需要帮助,想要旋转图像,3 秒后它必须以随机度数停止(从360
到10800
)。当我从最后一个位置单击它时,它开始旋转。
当图像停止时,它会出现一个带有我大量随机引用的区域。它必须是“旋转瓶子”之类的东西
请帮忙,我有一些代码,但不知道如何完成它。
.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">
解决方案
您可以使用 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">
推荐阅读
- python - 当测试数据集中的行被打乱时,分类性能会下降
- r - 使用 RStudio 和 Knitr,如何对特定列进行可变颜色编码?
- java - 解决或命名此消息的问题:'无权打开应用程序“ECGWorkbench”
- wso2 - WSO2 EI 6.5.0 在 SOAP 服务响应中启用 MTOM
- angular - 如何使 Mat-Table 中的列值成为超链接
- python - DRF ApiTest 在旧代码上运行,不更新
- python - 如何在模板中使用 Flask 的 url_for?
- c# - .Net 5 中的 HttpRequestMessage.Content 替代方案
- python - Plotly Choropleth 不使用 ISO 代码显示颜色
- r - 基于字符串值的子集数据