首页 > 利用嵌套的div的宽度变化做类似进度条的效果

利用嵌套的div的宽度变化做类似进度条的效果

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#wrap{width:500px;height:50px;margin-top:200px;position:relative;border:1px solid #000;}
#bg{background-color:#9ceff7;width:0px;opacity:1;height:50px;}
span{font-size:25px;position:absolute;top:12px;}
</style>
<script>
window.onload=function(){
    var aSpan=document.getElementsByTagName("span");
    var oBg=document.getElementById("bg");
    var oWrap=document.getElementById("wrap");
    var str='';
    for (var i=0; i<10; i++){
        str+='<span style="top:12px; left:'+(20+i*45)+'px;">+'+i+'</span>';    
    }
    oWrap.innerHTML+=str;
    oWrap.onclick=function(){
        doMove(oBg,'width',10,500);
    }    
}
function doMove(object,attr,speed,target,endFn){
    clearInterval(object.moveTimer);
    if (target>parseInt(getStyle(object,attr))){
        speed=speed;    
    }else{speed=-speed;}
    object.moveTimer=setInterval(function(){
        var progress=parseInt(getStyle(object,attr))+speed;
        if (progress>=target&&speed>0||progress<=target&&speed<0){
            progress=target;    
        }
        object.style[attr]=progress+'px';
        if (progress===target){
            clearInterval(object.moveTimer);
            endFn&&endFn();    
        }    
    },30);    
}
function getStyle(object,attr){
    return object.currentStyle?object.cureentStyle[attr]:getComputedStyle(object)[attr];
}
</script>
</head>

<body>
<div id="wrap">
    <div id="bg"></div>
</div>
</body>
</html>

如上面的代码想做一个类似进度条的效果,没有报错,但是改不了oBg的宽度。如果我把span标签放在bg这个DIV里面就能够成功,为什么呢?小白在此谢过了。


贴代码建议不要截图

没错 问题就出在这一句上面

oWrap.innerHTML+=str;

这句话执行完, 文档中原来的 <div id="bg"> 节点已经被新的覆盖了。oBg 所指向的是老的<div id="bg">节点已经不在文档中了。所以之后所有对oBg 的操作实际上是不起作用的。

但是如果这样写

oBg.innerHTML+=str;

<div id="bg"> 节点并没有被替换,只是里面的内容变了。所以 oBg 任然指向文档中的节点。所以对 oBg 的操作有效。

【热门文章】
【热门文章】