循环未覆盖div的样式



function lineComplete() {
let line = document.getElementById("line");
for (let percentage = 0; percentage <= 100; percentage++) {
setTimeout(function() {
line.style.width = `${percentage}%`;
}, percentage * 25);
if (percentage === 100) {
undo();
}
}
function undo() {
for (let percent = 100; percent >= 0; percent--) {
setTimeout(function() {
line.style.width = `${percent}%`;
}, percent * 25);
}
}
}
#outLine {
width: 60%;
height: 20px;
margin: 10px 0px;
background-image: linear-gradient(to right, #f12711, #f12711);
border-radius: 20px;
}
#line {
background-image: linear-gradient(to right, #f12711, #f5af19);
height: 100%;
width: 100%;
border-radius: 20px;
}
<body onload="lineComplete()">
<div id="outLine">
<div id="line"></div>
</div>
</body>

在上面的片段中,我试图展示我能够实现的类似加载器的效果。问题是,当line的宽度为100%时,我正试图激发函数undo。这也很好。在undo中存在一个环路,它减小了line的宽度并逐渐使其宽度达到0%。循环也很好,因为我在用alert()替换其内容后尝试运行它,它运行得很好。但在目前的情况下,循环并没有调整line的大小。我认为它无法覆盖样式。

您可以这样简化代码。不需要forloop和setTimeout。

function lineComplete() {
let line = document.getElementById("line");
line.classList.add("active");
line.addEventListener("transitionend", () => {
line.classList.remove("active");
});
}
#outLine {
width: 60%;
height: 20px;
margin: 10px 0px;
background-image: linear-gradient(to right, #f12711, #f12711);
border-radius: 20px;
overflow: hidden;
}
#line {
background-image: linear-gradient(to right, #f12711, #f5af19);
height: 100%;
width: 0%;
border-radius: 20px;
transition: 2s linear;
}
#line.active {
width: 100%;
}
<body onload="lineComplete()">
<div id="outLine">
<div id="line"></div>
</div>
</body>

也可以只使用动画:

#outLine {
width: 60%;
height: 20px;
margin: 10px 0px;
background-image: linear-gradient(to right, #f12711, #f12711);
border-radius: 20px;
overflow: hidden;
}
#line {
background-image: linear-gradient(to right, #f12711, #f5af19);
height: 100%;
width: 0%;
border-radius: 20px;
transition: 4s linear;
}
#line.active {
animation: linecomplete 2s linear forwards;
/*                                you can use "infinite" instead of "forwards" if you want */
}
@keyframes linecomplete {
50% {
width: 100%;
}
}
<div id="outLine">
<div id="line" class="active"></div>
</div>

function lineComplete() {
let line = document.getElementById("line");
for (let percentage = 0; percentage <= 100; percentage++) {
setTimeout(function() {
line.style.width = `${percentage}%`;
if (line.style.width === "100%") {
undo();
}
}, percentage * 25);
}
function undo() {
for (let percent = 100; percent >= 0; percent--) {
setTimeout(function() {
line.style.width = `${100 - percent}%`;
}, percent * 25);
}
}
}
#outLine {
width: 60%;
height: 20px;
margin: 10px 0px;
background-image: linear-gradient(to right, #f12711, #f12711);
border-radius: 20px;
}
#line {
background-image: linear-gradient(to right, #f12711, #f5af19);
height: 100%;
width: 100%;
border-radius: 20px;
}
<body onload="lineComplete()">
<div id="outLine">
<div id="line"></div>
</div>
</body>

问题是,当您减少时,后面的迭代被安排为比前面的迭代更早运行。让我们否定百分比(100 - percentage),它会起作用。

最新更新