3 回答

TA貢獻1818條經驗 獲得超3個贊
請檢查此解決方案。我認為您正在嘗試恢復該值并像鐘擺一樣再次啟動循環,如果是這種情況,那么我希望這個解決方案會有所幫助。
.as-console-wrapper {
max-height: 20px !important;
}
.a {
transition: all 1s ease;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.a {
width: 100px;
height: 100px;
/* border: 1px solid red; */
background-color: red;
margin: 40px auto;
}
</style>
</head>
<body>
<div class="a">
</div>
<script>
let rotate = 60;
function first() {
let interval;
// Don't forget to clear the interval
if (interval) clearInterval(interval);
interval = setInterval( a, 1000);
}
function a() {
if(rotate === 60) rotate += 60;
else rotate -= 60;
console.log(rotate);
document.getElementsByClassName('a')[0].style.transform = `rotate(${rotate}deg)`;
}
window.addEventListener('load', first);
</script>
</body>
</html>

TA貢獻2051條經驗 獲得超10個贊
其實是在旋轉。您需要rotate按時更新該值。你可以試試這個——
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.a {
width: 100px;
height: 100px;
/* border: 1px solid red; */
background-color: red;
margin: 40px auto;
}
</style>
</head>
<body>
<div class="a">
</div>
<script>
var rotate = 0;
function first() {
let interval;
// Don't forget to clear the interval
if (interval) clearInterval(interval);
interval = setInterval( a, 1000);
}
function a() {
if (rotate > 360) rotate = 0;
rotate += 50;
document.getElementsByClassName('a')[0].style.transform = `rotate(${rotate}deg)`;
}
window.addEventListener('load', first);
</script>
</body>
</html>

TA貢獻1895條經驗 獲得超3個贊
您在一個函數 (a) 中同時調用這兩個 CSS 更改,并且該函數每秒觸發一次。事情就是這樣發生的,但速度很快。
在這個非常簡單的情況下你可以做的是這樣的:
function first() {
? ? const degs = ['rotate(50deg)', 'rotate(90deg)'];
? ? setInterval(() => {
? ? ? ? document.getElementsByClassName('a')[0].style.transform = degs[0];
? ? ? ? degs.reverse();
? ? }, 1000);
}
window.addEventListener('load', first);
這可行,但是......我會在這里使用 CSS 動畫。像這樣的東西也會帶來很好的平滑感:
<style>
? ? .a {
? ? ? ? width: 500px;
? ? ? ? height: 300px;
? ? ? ? /* border: 1px solid red; */
? ? ? ? background-color: #666;
? ? ? ? animation: exampleAnimation 2s infinite;
? ? }
? ? @keyframes exampleAnimation {
? ? ? ? 0% {
? ? ? ? ? ? transform: rotate(50deg);
? ? ? ? }
? ? ? ? 50% {
? ? ? ? ? ? transform: rotate(90deg);
? ? ? ? }
? ? ? ? 100% {
? ? ? ? ? ? transform: rotate(50deg);
? ? ? ? }
? ? }
</style>
- 3 回答
- 0 關注
- 134 瀏覽
添加回答
舉報