一个关于javascript 局部变量与全局变量的小问题

weixin_39820830 2017-08-12 10:33:04

<!-- 一???的?? -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>一???的????</title>
<style>
#divAdvert {
position: absolute;
font: 20pt Arial;
color:mediumspringgreen;
background-color:darkgrey;
left: 0;
top: 10px;
}
</style>
</head>
<body>
<div id="divAdvert">
?里是??的文字?容.
</div>
<script>
var switchDirection = false;

function doAnimation()
{

var divAdvertisement = document.getElementById("divAdvert");
var currentLeft = divAdvertisement.offsetLeft;
var newLocation;

if (!switchDirection)
{
newLocation = currentLeft + 2;
if (currentLeft >= 1080)
{
switchDirection = true;
}
}
else
{
newLocation = currentLeft - 2;
if (currentLeft <= 0)
{
switchDirection = false;
}
}
divAdvertisement.style.left = newLocation + "px";
}
setInterval(doAnimation, 10);
</script>
</body>
</html>

和<!-- 一???的?? -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>一???的????</title>
<style>
#divAdvert {
position: absolute;
font: 20pt Arial;
color:mediumspringgreen;
background-color:darkgrey;
left: 0;
top: 10px;
}
</style>
</head>
<body>
<div id="divAdvert">
?里是??的文字?容.
</div>
<script>
var switchDirection = false;

function doAnimation()
{

var divAdvertisement = document.getElementById("divAdvert");
var currentLeft = divAdvertisement.offsetLeft;
var newLocation;
var switchDirection = false;


if (!switchDirection)
{
newLocation = currentLeft + 2;
if (currentLeft >= 1080)
{
switchDirection = true;
}
}
else
{
newLocation = currentLeft - 2;
if (currentLeft <= 0)
{
switchDirection = false;
}
}
divAdvertisement.style.left = newLocation + "px";
}
setInterval(doAnimation, 10);
</script>
</body>
</html>

一个局部变量与全局变量的区别导致的动画不会往左移动的小bug,求问这个bug怎么导致的?
...全文
340 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_39820830 2017-08-13
  • 打赏
  • 举报
回复
[quote=引用 1 楼 showbo 的回复:] 局部变量每次执行doAnimation时 var switchDirection = false;这句都是赋值为false,所以if (!switchDirection)永远为真 全局变量只会当 if (currentLeft >= 1080) { switchDirection = true; }这种成立才会赋值 没有考虑到setInterval是让函数循环执行作用,局部变量的话函数每次执行局部变量都会被初始化,是一个死循环,找到答案了,谢谢大神的指点.
  • 打赏
  • 举报
回复
局部变量每次执行doAnimation时 var switchDirection = false;这句都是赋值为false,所以if (!switchDirection)永远为真 全局变量只会当 if (currentLeft >= 1080) { switchDirection = true; }这种成立才会赋值

推荐学习资料
JavaScript/Ajax开发技巧
JavaScript apply与call的用法及区别

87,993

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧