BuiltyRose 2012-03-17 23:14
浏览 209
已采纳

JS 简单计时问题

function coffee(){

var a= document.getElementById("cover").style.width;
var b= a.substring(0,3);//substring方法截取两个索引号之间的字符串
var picwidth=Number(b);

while(picwidth>0){
var i=0;
picwidth=picwidth-50;

var t=setTimeout("changeWidth(picwidth)",50);

}

}

function changeWidth(a){
document.getElementById("cover").style.width=a;
}

就是得不出正确的结果
我都试了一下 var t=setTimeout("changeWidth(picwidth)",50); 是这句话有问题。
希望的效果是触发coffee方法 每50ms id为cover的div的长度就变化一下 求高手指导

我知道jquery可以实现而且很简单,但是我要用纯js代码来实现

谢谢各位高手先

  • 写回答

1条回答 默认 最新

  • suziwen 2012-03-17 23:45
    关注

    1.[quote]setTimeout() 只执行 code 一次。如果要多次调用,请使用 setInterval() 或者让 code 自身再次调用 setTimeout()。[/quote]
    while循环,是不会等setTimeout执行完才执行下一次循环的

    2.
    因此你要让你的代码每50ms执行一次,那就得这样写

    setInterval(function(){},50);

    [code="js"]

    var picwidth= 0;
    function coffee(){

    var a= document.getElementById("cover").style.width;
    var b= a.substring(0,3);//substring方法截取两个索引号之间的字符串
    picwidth=Number(b);

    var t=setInterval(function(){
    if(picwidth <=0){
    clearInterval(t);
    }
    changeWidth(picwidth);
    picwidth=picwidth-50;
    },50);

    }

    function changeWidth(a){
    document.getElementById("cover").style.width=a;
    }
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示