js代码很长,但是问题很小。。为什么按“向左走”“向右走”的按钮,它没反应呢?好像是speed问题?

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title><style>*{margin: 0;padding:0;} #div1{width: 712px;height: 108px;margin: 100px auto;position:relative;background:lightblue;overflow: hidden;} #div1 ul{position: absolute;top: 0;left: 0;} #div1 ul li{float: left;width: 178px;height: 108px;list-style: none;}</style><script>window.onload=function(){ var oDiv=document.getElementById(✀div1✀); var oUl=oDiv.getElementsByTagName(✀ul✀)[0]; var aLi=oUl.getElementsByTagName(✀li✀); var speed=-2; oUl.innerHTML=oUl.innerHTML+oUl.innerHTML; oUl.style.width=aLi[0].offsetWidth*aLi.length+✀px✀; function move(){ if(oUl.offsetLeft<-oUl.offsetWidth/2){ oUl.style.left=✀0✀; } if(oUl.offsetLeft>0){oUl.style.left=-oUl.offsetWidth/2+✀px✀;} oUl.style.left=oUl.offsetLeft+speed+✀px✀ } var timer=setInterval(move,30); oDiv.onmouseover=function(){ clearInterval(timer) }; oDiv.onmouseout=function(){ timer=setInterval(move,30); }}; document.getElementsByTagName(✀a✀)[0].onclick=function () { speed=-2; }; document.getElementsByTagName(✀a✀)[1].onclick=function(){ speed=2;}</script></head><body><a href="javascript:">向左走</a><a href="javascript:">向右走</a><div id="div1"> <ul> <li><img src="img2/1.jpg"></li> <li><img src="img2/2.jpg"></li> <li><img src="img2/3.jpg"></li> <li><img src="img2/4.jpg"></li> </ul></div></body></html>
2026年09月24日 21:28
有1个网友回答
网友(1):

有问题先右键审查元素看看有没有报错啊,39行报错Uncaught TypeError: Cannot set property 'onclick' of undefined,没有获取到a元素嘛。。。
可能在获取元素时文档还没加载完毕
把两个getElementsByTagName都移到window.onload内正常了