gpt4 book ai didi

javascript - 在 Javascript 中使用时间延迟

转载 作者:行者123 更新时间:2023-11-30 12:58:16 26 4
gpt4 key购买 nike

我有一个 gif 图像,我想通过使高度和/或宽度可变来拉伸(stretch)它。但是,我希望图像拉伸(stretch)以我设置的速度完成,因此它是渐进的并且在屏幕上可见。下面的代码有效,但它立即将图像渲染为完整图像,没有可见的拉伸(stretch)。所以我想:插入某种计时器函数来减慢“拉伸(stretch)”代码的执行速度。我已经尝试过 setTimeout 和 setInterval(使用 1/100 秒延迟),但我无法使任何一个工作。伙计们,我做错了什么?

$(window).load(function(){

setInterval(function(){
var i=1;
for (i;i<400;i++) {
$("#shape1").html('<img src="image.gif" width="'+i+'" height="40">');
}
},10);
});

最佳答案

你的代码的问题是

  • 在每个间隔迭代中,重复整个 for 循环
  • 你永远不会停止间隔循环

您可以像这样修复现有代码:

var i=1;
function step() {
$("#shape1").html('<img src="image.gif" width="'+i+'" height="40">');
if (i++<400) setTimeout(step, 10);
}
step();

无需每次都替换 #shape1 内容,您还可以简单地更改宽度:

var i=1;
var $img = $('<img src="image.gif" width=1 height="40">').appendTo('#shape1');
function step() {
$img.css('width', i);
if (i++<400) setTimeout(step, 10);
}
step();

Demonstration

但是jQuery有一个非常方便的animate功能只是为了这种事情。

关于javascript - 在 Javascript 中使用时间延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297175/

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