有没有办法让一个元素旋转而不让变量告诉它已经转动了多远?



我有一个播放音乐的实验性网站,我希望前进和后退按钮在单击它们时旋转。但是,我也不想让 2 个变量来表示它们转动了多远,或者有一个函数来获取它们从 CSS transform 属性转了多远。它们有一个过渡,用于悬停效果。我试过了

backward.classList.add("notrans");
backward.style.transform = "rotateZ(0deg)";
backward.classList.remove("notrans");
backward.style.transform = "rotateZ(-360deg)";

和一些密切相关的东西,并且还有一个设置超时来重置它,它太长了,不适合发布。

Animate就是您要搜索的内容。这应该是一个工作示例:(在FF和Chrome中测试(

/* THIS IS A JAVASCRIPT CLASS THAT ADDS AND
REMOVES THE CSS CLASS FROM YOUR ELEMENT
USING THE ELEMENT'S ID VALUE TO REFERENCE. */
function startStop(strstp) {
var infinite = document.getElementById("imSpinning");
var once = document.getElementById("imSpinningOnce");

if(strstp == 1)
{
infinite.classList.add("spin");
once.classList.add("spinOnce");
timer = setTimeout(function() {
once.classList.remove("spinOnce");
},1000); 
}
else
{
infinite.classList.remove("spin");
once.classList.remove("spinOnce");
}
}
/* THIS IS THE CSS CLASS THAT CREATES INFINITE ROTATION */
.spin {
-webkit-animation:spin 1s linear infinite;
-moz-animation:spin 1s linear infinite;
animation:spin 1s linear infinite;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
/* THIS IS THE CSS CLASS THAT ROTATES ONCE */
.spinOnce {
-webkit-animation:spin 1s linear;
-moz-animation:spin 1s linear;
animation:spin 1s linear;
}
@-moz-keyframes spinOnce { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spinOnce { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spinOnce { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
<div style="width: 100px; height: 30px; background-color: green; color: white; margin: 20px; text-align: center; cursor: pointer;" onclick="startStop(1)">
GO
</div>
<div style="width: 100px; height: 30px; background-color: red; color: white; margin: 20px; text-align: center; cursor: pointer;" onclick="startStop(0)">
STOP
</div>
<!-- ELEMENT TO ROTATE INFINITLY WITH "spin" CLASS -->
<div id="imSpinning" class="spin" style="position: absolute; top: 10px; right: 30px; height: 140px; width: 140px; background-image: url(https://icons.iconarchive.com/icons/thehoth/seo/256/seo-web-code-icon.png); background-size: 100% 100%; background-position: center center; border-radius: 50%; overflow: hidden;"></div>
<!-- ELEMENT TO ROTATE ONCE WITH "spin" CLASS -->
<div id="imSpinningOnce" class="spinOnce" style="position: absolute; top: 10px; right: 200px; height: 140px; width: 140px; background-image: url(https://icons.iconarchive.com/icons/thehoth/seo/256/seo-web-code-icon.png); background-size: 100% 100%; background-position: center center; border-radius: 50%; overflow: hidden;"></div>

只需将上面的 CSS 类复制到页面的样式部分/工作表中,然后根据需要对其进行修改即可。确保在 html 元素中引用该类。

我还编辑了一个小型 JavaScript 类,如果它可以帮助您启动和停止动画,它会从 DIV 元素中添加/删除旋转类。

希望这有帮助,祝你好运!

最新更新