<!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>
<style type="text/css"> 
#showtext{position:absolute;top:0px;left:0px;}
</style>
<script type="text/javascript"> 
 function setTimeMove()
{
 setInterval("moveText()",10);
}
 function moveText()
{
 var switchdirection=false;
 var showtext=document.getElementById("showtext");
 var currentleft=showtext.offsetLeft;
 var newlocation;
 if (switchdirection==false)
 {
  newlocation=currentleft+2;
  if (currentleft>=800)
  {
    switchdirection=true;
  }
 }
 else
 {
  newlocation=currentleft-2;
  if (currentleft<=0)
   {
    switchdirection=false;  
   }
  }
 showtext.style.left=newlocation+"px";
}
</script>
</head>
<body onload="setTimeMove()">
<div id="showtext">元素的内容</div>
</body>
</html>上面这段代码,期望出现的是div中的文字从左到右来回浮动,但是运行后却是从左至右单向浮动,不能返回。是哪里的错误呢?

解决方案 »

  1.   

    你每10毫秒执行一遍方法,上来就执行var switchdirection=false;所以 if (switchdirection==false)
     {
      newlocation=currentleft+2;
      if (currentleft>=800)
      {
        switchdirection=true;
      }
     }这段永远成立执行,一直向右走
      

  2.   

    你应该把标志位弄到方法外面<!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>
    <style type="text/css"> 
    #showtext{position:absolute;top:0px;left:0px;}
    </style>
    <script type="text/javascript"> 
     function setTimeMove()
    {
     switchdirection=false;
     setInterval("moveText()",10);
    }
     function moveText()
    {
     //var switchdirection=false;
     var showtext=document.getElementById("showtext");
     var currentleft=showtext.offsetLeft;
     var newlocation;
     if (switchdirection==false)
     {
      newlocation=currentleft+2;
      if (currentleft>=800)
      {
        switchdirection=true;
      }
     }
     else
     {
      newlocation=currentleft-2;
      if (currentleft<=0)
       {
        switchdirection=false;  
       }
      }
     showtext.style.left=newlocation+"px";
    }
    </script>
    </head>
    <body onload="setTimeMove()">
    <div id="showtext">元素的内容</div>
    </body>
    </html>
      

  3.   

     var switchdirection=false;
    定义到函数外面