gpt4 book ai didi

JavaScript setTimeout() 动画方法

转载 作者:行者123 更新时间:2023-12-02 20:24:22 24 4
gpt4 key购买 nike

我有三个黄色条,每个都需要从左到右。为此,我生成了这段代码,但它只适用于最后一个。任何人都可以更正此代码吗?我需要使用纯 JavaScript。我没有使用任何框架。谢谢。

window.onload = function(){  

var yellowTitles = document.getElementById('magazine-brief').getElementsByTagName('h2');

for(i=0; i< yellowTitles.length; i++) {
var header = yellowTitles[i];
var timer = i*500;
var yellowBar = setTimeout(animeYellowBar,timer);

function animeYellowBar(){
header.style.left= "0";
}

}

}

最佳答案

这是我解决问题的方法:

var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');

// this will force the header number to be bound correctly
// also animates the div across the page by tracking the current position of x
function createMotion(num){
var currPos = 0;//current x position
var delta = 10;//move by this amount
setInterval(function(){
currPos += delta
yellows[num].style.left = currPos;
}, num * 500);
}

for (var i = 1; i < yellows.length; i++)
{
createMotion(i);
}

注意添加了“createMotion”函数,以便在 setInterval 函数中正确引用数字“i”。

关于JavaScript setTimeout() 动画方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5077298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com