3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
請(qǐng)檢查此解決方案。我認(rèn)為您正在嘗試恢復(fù)該值并像鐘擺一樣再次啟動(dòng)循環(huán),如果是這種情況,那么我希望這個(gè)解決方案會(huì)有所幫助。
.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貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
其實(shí)是在旋轉(zhuǎn)。您需要rotate按時(shí)更新該值。你可以試試這個(gè)——
<!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貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
您在一個(gè)函數(shù) (a) 中同時(shí)調(diào)用這兩個(gè) CSS 更改,并且該函數(shù)每秒觸發(fā)一次。事情就是這樣發(fā)生的,但速度很快。
在這個(gè)非常簡(jiǎn)單的情況下你可以做的是這樣的:
function first() {
? ? const degs = ['rotate(50deg)', 'rotate(90deg)'];
? ? setInterval(() => {
? ? ? ? document.getElementsByClassName('a')[0].style.transform = degs[0];
? ? ? ? degs.reverse();
? ? }, 1000);
}
window.addEventListener('load', first);
這可行,但是......我會(huì)在這里使用 CSS 動(dòng)畫(huà)。像這樣的東西也會(huì)帶來(lái)很好的平滑感:
<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 關(guān)注
- 132 瀏覽
添加回答
舉報(bào)