请教达人,为什么这段代码运行不正常?JScript code!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transiti
请教达人,为什么这段代码运行不正常?
JScript code<!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中的文字从左到右来回浮动,但是运行后却是从左至右单向浮动,不能返回。是哪里的错误呢?
[解决办法]你应该把标志位弄到方法外面
<!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>
[解决办法] var switchdirection=false;
定义到函数外面